questionto42
questionto42

Reputation: 9502

A working RegEx match that begins at the first of two OR-words takes the unwanted last OR-word instead if I place more RegEx before it

For this String:

SELECT a, bc d AS Error FROM y WHERE 1=1 HAVING 1=1

I need to get two matching groups:

  1. bc d as the code that builds the column called "Error". This is dummy code, do not care about the SQL.

  2. Anything after one of the two words "WHERE" or "HAVING".

Check 1 (working)

(?<=WHERE|HAVING)(.*)

enter image description here

This works with a positive lookbehind, taken from How to match the first word after an expression with regex? - Stack Overflow. This is the second match that I need. It finds the first of two OR-words as the beginning of the match.

Check 2 (working)

Getting the last of the two OR-words as a match works as well, here with a positive lookahead since it is the other way round of Check 1:

(?>=SELECT\s+|,\s*)(.+)\s+AS\s+Error

enter image description here

Check 3 (the question)

If I put the two together with .* in the middle, this will only match after HAVING, but not after WHERE, though that is the first of the two searchwords and should be the beginning of the match - and as far as I understand it right, the positive lookbehind should take care of stopping the greedy .*. And it does, but only at the second word of the two OR-words.

(?>=SELECT\s+|,\s*)(.+)\s+AS\s+Error.*(?<=WHERE|HAVING)(.*)

enter image description here

How do I get the "Group 1" (as in Check 1 above) as in the Regex101 screenshot which already works, but also "Group 2" as I underlined red (as in Check 2 above) instead of this too late match?

For the checks, I took the default language and flavour of www.regex101.com, which is PCRE2 (PHP >=7.3) at the time of writing:

enter image description here

Upvotes: 1

Views: 47

Answers (0)

Related Questions