如何将方括号内的数字与regex匹配

时间:2022-07-20 21:43:01

I wrote a regular expression which I expect should work but it doesn't.

我写了一个正则表达式,我希望它可以工作,但它不行。

  var regex = new RegExp('(?<=\[)[0-9]+(?=\])')

Javascript is giving me the error Invalid regular expression :(/(?<=[)[0-9]+(?=])/): Invalid group

Javascript给了我一个错误无效的正则表达式:(/(?<=[][0-9]+(?=])/:无效组

Does javascript not support lookahead or lookbehind?

javascript不支持前向或后向吗?

4 个解决方案

#1


17  

This should work:

这应该工作:

var regex = /\[[0-9]+\]/;


edit: with a grouping operator to target just the number:

var regex = /\[([0-9]+)\]/;

With this expression, you could do something like this:

有了这个表达式,你可以做这样的事情:

var matches = someStringVar.match(regex);
if (null != matches) {
  var num = matches[1];
}

#2


2  

Lookahead is supported, but not lookbehind. You can get close, with a bit of trickery.

前视得到支持,但不支持后视。你可以靠得很近,用一点小技巧。

#3


1  

To increment multiple numbers in the form of lets say:

以让我们说:

var str = '/a/b/[123]/c/[4567]/[2]/69';

Try:

试一试:

str.replace(/\[(\d+)\]/g, function(m, p1){
 return '['+(p1*1+1)+']' }
)

//Gives you => '/a/b/[124]/c/[4568]/[3]/69'

#4


0  

If you're quoting a RegExp, watch out for double escaping your backslashes.

如果您正在引用RegExp,请注意避免重复使用反斜杠。

#1


17  

This should work:

这应该工作:

var regex = /\[[0-9]+\]/;


edit: with a grouping operator to target just the number:

var regex = /\[([0-9]+)\]/;

With this expression, you could do something like this:

有了这个表达式,你可以做这样的事情:

var matches = someStringVar.match(regex);
if (null != matches) {
  var num = matches[1];
}

#2


2  

Lookahead is supported, but not lookbehind. You can get close, with a bit of trickery.

前视得到支持,但不支持后视。你可以靠得很近,用一点小技巧。

#3


1  

To increment multiple numbers in the form of lets say:

以让我们说:

var str = '/a/b/[123]/c/[4567]/[2]/69';

Try:

试一试:

str.replace(/\[(\d+)\]/g, function(m, p1){
 return '['+(p1*1+1)+']' }
)

//Gives you => '/a/b/[124]/c/[4568]/[3]/69'

#4


0  

If you're quoting a RegExp, watch out for double escaping your backslashes.

如果您正在引用RegExp,请注意避免重复使用反斜杠。