简体   繁体   中英

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

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM