高分求一正则表达式

faib920 2009-07-25 05:54:50
小弟想请教大侠,这个正则应该怎么写
我想把类似 select code,name from table1 where code in (select code from table2) order by code 的语句转换为
select count(1) from table1 where code in (select code from table2)
也就是输入任意的一个sql语句,转换为可以查询出记录数的语句。在线求教。
...全文
60 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
gsk09 2009-08-18
  • 打赏
  • 举报
回复

resultSQL=Regex.Replace(yourSQL, "^(?is)select.+?from", "select count(*) from ")
-过客- 2009-07-25
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 faib920 的回复:]
我现在这样写
                        regx = new Regex(@"select(\W|\w|\s)*from", RegexOptions.IgnoreCase);
                        commandText = regx.Replace(commandText, "select count(1) from");
                        regx = new Regex(@"order by(\W|\w|\s)*", RegexOptions.IgnoreCase);
                        commandText = regx.Replace(commandText, "");

但是后面的子查询也会被替换,期待好的代码
[/Quote]

为什么不考虑用幂白兄的处理方式
这里用正则处理局限性比较大,如果select 和from之间有子查询会是比较麻烦的

regx = new Regex(@"(?<=^\s*select\s)(?:(?!\bfrom\b).)+(?=\sfrom)", RegexOptions.IgnoreCase); 
commandText = regx.Replace(commandText, "count(1)");
regx = new Regex(@"order\s+by\s+\w+", RegexOptions.IgnoreCase);
commandText = regx.Replace(commandText, "");
faib920 2009-07-25
  • 打赏
  • 举报
回复
我现在这样写
regx = new Regex(@"select(\W|\w|\s)*from", RegexOptions.IgnoreCase);
commandText = regx.Replace(commandText, "select count(1) from");
regx = new Regex(@"order by(\W|\w|\s)*", RegexOptions.IgnoreCase);
commandText = regx.Replace(commandText, "");

但是后面的子查询也会被替换,期待好的代码
faib920 2009-07-25
  • 打赏
  • 举报
回复
顶顶
kkun_3yue3 2009-07-25
  • 打赏
  • 举报
回复
我写得比较烂,而且必须指定table1,期待更好的答案
(?<=select) .+ (?=from table1)
cpp2017 2009-07-25
  • 打赏
  • 举报
回复
简单一点的。


sql = "select count(1) as c from ("+ sql +") AS AA " ;

110,538

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧