Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match string with Regex as long as it is not surrounded by parentheses

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

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

Should not match:

  • Select X from Y (order by z)
  • Select a.a, NTILE(4) OVER (Order by a.b) group by a.c

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?

like image 769
Yaakov Ellis Avatar asked Jun 14 '12 14:06

Yaakov Ellis


People also ask

How do you escape parentheses in regex?

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.

What is difference [] and () in regex?

[] 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 .

What does \f mean in regex?

Definition and Usage The \f metacharacter matches form feed characters.


1 Answers

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>
like image 58
Damian Powell Avatar answered Sep 17 '22 14:09

Damian Powell