JavaScript RegEx,与OR的零长度匹配(可以前后看)

时间:2012-07-03 16:47:03

标签: regex lookaround

我有这个正则表达式/\b\d\b/,只需匹配一个数字字。

现在我想添加下划线字符作为单词边界的替代,所以我想匹配"_1_"中的数字,同时将下划线保持为零长度匹配(如\ b,所以我不希望匹配中的_。)

我在使用捕获组的情况下并不理想。

我尝试了一些积极的前瞻/后方技巧,前瞻似乎工作,而后面的外观没有。尝试做可选的前瞻/后退,并做_|\b之类的事情,但我找不到理想的解决方案。

对于高级RegEx技巧不是很了解,我以为在用2个RegExes做这个之前我会问:)

这将在JavaScript中执行。

2 个答案:

答案 0 :(得分:2)

(?<=\b|_)\d(?=\b|_)

(?<=    # Positive look-behind
\b      # Word boundary
|       # Or
_       # Underscore
)       # End group
\d      # Digit
(?=     # Positive look-ahead
\b|_)   # Word boundary or underscore

它将与您的单个数字匹配,并将使用字边界(\b)或下划线(_)来匹配。

这是零长度,所以它不会将它匹配的数字分组。

Play with the regex here

答案 1 :(得分:0)

由于后视镜不能在JS中工作,因此您只能为主要正则表达式匹配\d,然后手动检查边界。

const manualBoundaries = /\d/g
const matches = [];
while ((match = manualBoundaries.exec(str)) !== null) {
  const m = match[0]
  const i = match.index
  if ((i == 0 || str[i - 1].match(/(\W|_)/)) &&
      (i + m.length == str.length || str[i + m.length].match(/(\W|_)/)))
    matches.push(m)
}

或者更简洁,假装替换

const matches = [];
str.replace(manualBoundaries, (m, i) => {
    if ((i == 0 || str[i - 1].match(/(\W|_)/)) &&
        (i + m.length == str.length || str[i + m.length].match(/(\W|_)/)))
      matches.push(m);
});

在此处试试:https://jsfiddle.net/djjeck/mg2gzpf1/