Match string with regex if it is not surrounded by parentheses

I'm looking for matching string "Order By XXX", where XXX can be any letter, number, period, comma, space or square bracket. However, I would only like to compare this if it is not surrounded by parentheses (the brackets on one side are okay, if it is not on both sides). Therefore, it must correspond to the italicized course from "", since it must not correspond to anything in

Corresponds (section in italics):

  • Choose X from Y order on z
  • Choose y = (select top 1 Z from C Order by [ID] desc)

Cannot match:

  • Choose X from Y (z order)
  • Select group aa, NTILE (4) OVER (Order by ab) with ac

I have a string of regular expressions to match the order in the text: [ ]*order by [\w,.\[\] ]+ . However, I have some problems getting an idea / at work properly. Any tips on how to proceed?

+8
c # regex lookbehind lookahead
source share
3 answers

Try the following:

 (?<!\(\s*)order\s+by\s+[\w,.\[\] ]+(?<!\s*\)) 

When testing in PowerShell:

 PS> @( 'Select X from Y order by z' 'Select y = (select top 1 Z from C Order by [ID] desc)' 'Select X from Y (order by z)' 'Select aa, NTILE(4) OVER (Order by ab) group by ac' 'Order by 87' '(Order by 87)' '( Order by 87 )' '(Order by 87 )' '( Order by 87)' 'Order by _foo' ) -match '(?<!\(\s*)order\s+by\s+[\w,.\[\] ]+(?<!\s*\))' Select X from Y order by z Select y = (select top 1 Z from C Order by [ID] desc) Order by 87 Order by _foo PS> 
+1
source share

This works for me, let me know if there are other cases that I am missing:
Regex r = new Regex(@"[^(](order by [^)]+)", RegexOptions.IgnoreCase);

0
source share

you can use alternation as follows:

 \(?(order by [a-z0-9., \[\]]+)(?![a-z0-9., \[\]])(?<!\))|[^(](order by [a-z0-9., \[\]]+)\) 

"order by XXX" will either be captured by the first or second sliding brackets.

-one
source share

All Articles