【问题标题】:Why doesn't positive lookahead work as first capture group?为什么积极的前瞻性不能作为第一个捕获组?
【发布时间】:2014-11-28 12:46:33
【问题描述】:

我正在使用以下正则表达式;

((?:_missing_:|_exists_:)[a-z0-9]+)|(([a-z0-9]+)(?=:))

匹配一个lucene查询字符串;

_missing_:title age:(>=10 AND < 20) AND age:123 AND _exists_:title123

不尊重第一个非捕获组并返回 _missing_:title 而不是 title。使用积极的前瞻会使整个正则表达式无法匹配任何内容。

它应该返回以下数组;

['title', 'age', 'age', 'title123']

【问题讨论】:

  • 这是一个 PoC,所以错过了,但谢谢。

标签: javascript regex regex-lookarounds


【解决方案1】:

如下更改您的正则表达式,然后从组索引 1 和 2 中获取您想要的字符串。

(?:_missing_:|_exists_:)([a-z1-9]+)|([a-z1-9]+)(?=:)

您不需要在捕获组中包含非捕获组(?:_missing_:|_exists_:)。这就是返回 missing:title 而不是 title 的原因。并且为[a-z1-9]+ 捕获组就足够了。

DEMO

【讨论】:

  • 当然,我尝试了很多变体,但使用 JavaScript 中的 match 函数仍然无法正确返回。返回 [ 'missing:title', 'age', 'age', 'exists:ti123tle' ]
  • string.match 只给出结果。您需要将第 1 组和第 2 组捕获推送到数组中。
猜你喜欢
  • 2020-02-05
  • 1970-01-01
  • 1970-01-01
  • 2019-10-17
  • 2012-02-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多