I am looking to match a string "Order By XXX" where XXX can be any letter, number, period, comma, space or square bracket. However, I would only like to match this if it is not surrounded by parentheses (parentheses on one side is ok, as long as it it not on both sides). So it should match the part in italics from "", by it should not match anything in
Should match (matched section in italics):
Should not match:
I have the regex string for matching the order by text: [ ]*order by [\w,.\[\] ]+
. However, I am having some trouble getting the lookahead/behind the work properly. Any advice on how to proceed?
Since parentheses are also used for capturing and non-capturing groups, we have to escape the opening parenthesis with a backslash. An explanation of how literalRegex works: / — Opens or begins regex. \( — Escapes a single opening parenthesis literal.
[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9. (a-z0-9) -- Explicit capture of a-z0-9 .
Definition and Usage The \f metacharacter matches form feed characters.
Try this:
(?<!\(\s*)order\s+by\s+[\w,.\[\] ]+(?<!\s*\))
When tested 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 a.a, NTILE(4) OVER (Order by a.b) group by a.c'
'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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With