1

需要复合表达式

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

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

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

string pat = @"^((?!\(.* 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 日上午 8:05 在以下链接中的回复...

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

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

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

我已经学习/搜索了大约一周,但对我来说仍然很复杂:)

4

2 回答 2

2

即使使用任意嵌套的括号,以下内容也应该有效:

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
       \( (?<DEPTH>)   #  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>))*(?(DEPTH)(?!))\))*[^()]*\z)"))
于 2012-08-17T11:17:14.737 回答
1

这可能是你想要的。

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");
于 2012-08-17T11:10:32.037 回答