Search code examples
javascriptregexnon-greedy

Regex lazy on non-capturing group


I have this regex:

(?:(?:AND\sNOT|AND|OR)(?!.*(?:AND\sNOT|AND|OR))\s)(.*)

What I want is to get the last key:value pair, example -

k:v AND k1:v1 AND NOT k2:v2 OR k3:v3

I want the regex to match k3:v3, and it does, but it doesn't match the key:value in the next situation -

k:v

I need it to match the key:value pair even if it's the first one and there's no operators brefore...

update: key:value is not the issue here, I need it to match everything after the last operator

update 2: tried to do the following -

(?:(?:AND\sNOT|AND|OR)?(?!.*(?:AND\sNOT|AND|OR))\s)(.*)
(?:(?:AND\sNOT|AND|OR?)(?!.*(?:AND\sNOT|AND|OR))\s)(.*)

didn't work


Solution

  • Edit - My bad, \K isn't supported in JS. Here's an alternative one:

    /(?:.*(?:AND|OR|NOT)\s+)?(.*)/ (group 1)

    https://regex101.com/r/AyVV89/3 (Please check the matches on the right panel, for some reason group 1 isn't highlighted on the text.)

    Original post

    Per your last update (that wasn't obvious at all before you mentioned it):

    key:value is not the issue here, I need it to match everything after the last operator

    This one will match anything after the last operator, no matter what it is (and work without an operator too):

    /(?:.*(?:AND|OR|NOT)\s+\K)?.*/

    https://regex101.com/r/AyVV89/2