Find a pattern to match 'a', ignoring that 'a' which lies within 'b' and 'c'

后端 未结 2 1313
你的背包
你的背包 2021-01-25 16:15

Need a compound expression for

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

(ignoring those which are in parenthesi

相关标签:
2条回答
  • 2021-01-25 16:52

    The following should work, even with arbitrarily nested parentheses:

    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))
    

    As a single line regex ("The horror! The horror!"), if you insist:

    if (Regex.IsMatch(subjectString,@"\sfrom(?=(?:[^()]*\((?>[^()]+|\((?<DEPTH>)|\)(?<-DEPTH>))*(?(DEPTH)(?!))\))*[^()]*\z)"))
    
    0 讨论(0)
  • 2021-01-25 17:05

    This may be what you want.

    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");
    
    0 讨论(0)
提交回复
热议问题