Need a compound expression for
\" from\" such that \" from\" is not within parenthesis
(ignoring those which are in parenthesi
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)"))
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");