简体   繁体   English

正则表达式对非捕获组懒惰

[英]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 - 我希望正则表达式匹配k3:v3,它确实匹配,但它与下一个情境中的键:值不匹配 -

k:v

I need it to match the key:value pair even if it's the first one and there's no operators brefore... 我需要它来匹配键:值对,即使它是第一个并且没有运算符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 - 更新2:尝试执行以下操作 -

(?:(?: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. 编辑 - 我的坏,在JS中不支持\\K Here's an alternative one: 这是另一种选择:

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

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.) https://regex101.com/r/AyVV89/3 (请检查右侧面板上的匹配项,由于某种原因,文本中未突出显示组1。)

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 key:value不是问题,我需要它匹配最后一个运算符后的所有内容

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 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 (?:AND(?:\\sNOT)?|OR)匹配ANDAND NOTOR
  • \\s+ match any number of whitespaces \\s+匹配任意数量的空格
  • (\\S+) match and capture none-whitespace characters (\\S+)匹配并捕获无空白字符
  • $ asserts end of string $ asserts字符串结尾

From your explanation, you don't need the first operator at all. 根据您的解释,您根本不需要第一个操作员。 Simply try 试试吧

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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