找到一个匹配’a’的模式,忽略’a’位于’b’和’c’之内

需要复合表达式

" from" such that " from" is not within parenthesis 

(忽略括号中的那些)这里a=" from"; b="("; and c=")"; a=" from"; b="("; and c=")";

我能写的最接近(但无效)的模式是

 string pat = @"^((?!\(.* from.*\)).)* from((?!\(.* from.*\)).)*$"; 

我的表达式否认括号中是否有“from”但我想严格忽略这样的“来自”

匹配应该在:

 1: " from" 2:select field1 from t1 (select field1 from t1) ---- 1 time in both 3: select field1 from t1 (select field1 from t1)select field1 from t1 ---2 times 

不包含匹配的字符串:(因为我想忽略括号内的“from”)

 1: select field1 no_f_rom_OutOf_Parenthesis t1 (select field1 from t1) 2: (select field1 from t1) 3: "" (Empty String) 4. No word as form 0 times in all four strings 

相关材料:(不太需要阅读)

关于如何匹配’模式’但不是’常规’的问题更接近我的问题的最有用的链接是stanav在2009年7月31日上午08:05在以下链接中的回复…

http://www.vbforums.com/archive/index.php/t-578417.html

另外: C#中的正则表达式包含“this”而不是“that”

另外: 正则表达式匹配不包含单词的行?

我已经研究/搜索了大约一个星期,但对我来说仍然很复杂:)

以下应该可以工作,即使使用任意嵌套的括号:

 if (Regex.IsMatch(subjectString, @"\sfrom # Match ' from' (?= # only if the following regex can be matched here: (?: # The following group, consisting of [^()]* # any number of characters except parentheses, \( # followed by an opening ( (?> # Now match... [^()]+ # one or more characters except parentheses | # or \( (?) # a (, increasing the depth counter | # or \) (?<-DEPTH>) # a ), decreasing the depth counter )* # any number of times (?(DEPTH)(?!)) # until the depth counter is zero again, \) # then match the closing ) )* # Repeat this any number of times. [^()]* # Then match any number of characters except () \z # until the end of the string. ) # End of lookahead.", RegexOptions.IgnorePatternWhitespace)) 

作为单行正则表达式(“恐怖!恐怖!”),如果你坚持:

 if (Regex.IsMatch(subjectString,@"\sfrom(?=(?:[^()]*\((?>[^()]+|\((?)|\)(?<-DEPTH>))*(?(DEPTH)(?!))\))*[^()]*\z)")) 

这可能就是你想要的。

 string s="select field1 dfd t1 (select field1 from t1)select field1 from t1"; Regex r=new Regex(@"(?<=\)|^)\bselect\b.*?\bfrom\b.*?(?=\()",RegexOptions.RightToLeft); r.Replace(s,"HELL yeah");