Nadav Shabtai
Nadav Shabtai

Reputation: 687

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

Upvotes: 3

Views: 300

Answers (3)

Jeto
Jeto

Reputation: 14927

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

Upvotes: 2

revo
revo

Reputation: 48711

Update

As per comments, I assume you need to match last key:value pair along with its operator if any, and anything that comes after:

(?:.*\b(AND(?:\sNOT)?|OR) +)?(\S+:\S+.*)

Live demo


What you need could be simplified into this:

(?:AND(?:\sNOT)?|OR)\s+(\S+)$

Live demo

  • (?:AND(?:\sNOT)?|OR) match AND or AND NOT or OR
  • \s+ match any number of whitespaces
  • (\S+) match and capture none-whitespace characters
  • $ asserts end of string

Upvotes: 1

AndreyS Scherbakov
AndreyS Scherbakov

Reputation: 2778

From your explanation, you don't need the first operator at all. Simply try

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

Upvotes: 0

Related Questions