大家好,我想请教大家一个正则表达式应该怎么写。下面是一种OQL(object query language), 我现在想验证它是否包含那个id。在括号中的是子语句,他们也有可能包含“id”, 正则表达式需要能区分主语句中的id和子语句中的id,只验证主语句是是否有id。谢谢大家!select name, id, country, city, (select id, firstname, lastname from contacts), (select id, name, amount from opportunities) from account where name like '%a%'
select name, id, country, city, (select id, firstname, lastname from contacts), (select id, name, amount from opportunities) from account where name like '%a%'
考虑到select的多重嵌套。彻底解决这个问题需要用到递归匹配。虽然不算很难,但是写起来就够让人头大了。可考虑的建议:1、用C#写一个解析程序,返回结果。
个人想法:写这个解析程序都比写正则要简单!对俺们来说,正则的可读性不是很好。(大牛是例外)。
2、要彻底解决多重嵌套,自己去研究一下递归匹配的语法。一下,看看有没有牛人解决这个问题。(这个匹配够难度了)
string result = Regex.Replace(strOQL, @"\(((\((?<o>)|\)(?<-o>)|[^()])*(?(o)(?!)))\)", "");
if (Regex.IsMatch(result, @"\bid\b"))
MessageBox.Show("包含");
else
MessageBox.Show("不包含");
要进行sql断句~~比如:select top 10 name,id,city...
以空格和逗号断句,遇到括号则排除,比如那个10可能经过函数计算的..那么就有可能出现任何字符,得看(号~~
其实这已经涉及到编译原理的知识了。。并不是想象中那么简单~~
换个思路 先把字符串的的'('和')'还有其中间的内容去掉
这样就剩下主语句了 再看其中是否有"id"
我的代码 bool IsExistID(string str)
{
string s=str;
int start, end;
while(true) //循环找"(.....)"
{
start = s.IndexOf('(');
if (start == -1)
break;
end = s.IndexOf(')', start);
s=s.Remove(start, end - start + 1); //将"(.....)"删掉
}
if (s.IndexOf("id")>=0) //查看剩下的主语句中是否有"id"
return true;
else
return false;
}
换个思路 先把字符串的的'('和')'还有其中间的内容去掉
这样就剩下主语句了 再看其中是否有"id"
我的代码 bool IsExistID(string str)
{
string s=str;
int start, end;
while(true) //循环找"(.....)"
{
start = s.IndexOf('(');
if (start == -1)
break;
end = s.IndexOf(')', start);
s=s.Remove(start, end - start + 1); //将"(.....)"删掉
}
if (s.IndexOf("id")>=0) //查看剩下的主语句中是否有"id"
return true;
else
return false;
}
string result = Regex.Replace(strOQL, @"\(((\((?<o>)|\)(?<-o>)|[^()])*(?(o)(?!)))\)", "");
result = Regex.Replace(result, @"where[\s\S]*$", "", RegexOptions.IgnoreCase);
if (Regex.IsMatch(result, @"\b(?<!\.)id\b"))
MessageBox.Show("包含");
else
MessageBox.Show("不包含");
string result = Regex.Replace(strOQL, @"\(((\((?<o>)|\)(?<-o>)|[^()])*(?(o)(?!)))\)", "");
result = Regex.Replace(result, @"\bfrom\b[\s\S]*$", "", RegexOptions.IgnoreCase);
if (Regex.IsMatch(result, @"\b(?<!\.)id\b"))
MessageBox.Show("包含");
else
MessageBox.Show("不包含");
string result = Regex.Replace(yourStr, @"\(((\((?<o>)|\)(?<-o>)|[^()])*(?(o)(?!)))\)|\bfrom\b[\s\S]*$", "", RegexOptions.IgnoreCase);
if (Regex.IsMatch(result, @"\b(?<!\.)id\b"))
MessageBox.Show("包含");
else
MessageBox.Show("不包含");