javascript 如何将方括号内的数字与正则表达式匹配
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3444656/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I match a number inside square brackets with regex
提问by Teddy
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 给了我错误 Invalid regular expression :(/(?<=[)[0-9]+(?=])/): Invalid group
Does javascript not support lookahead or lookbehind?
javascript 不支持前瞻或后视吗?
回答by jmar777
This should work:
这应该有效:
var regex = /\[[0-9]+\]/;
edit编辑:使用分组运算符来定位数字:
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];
}
回答by Andy E
回答by user3751385
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'
回答by spender
If you're quoting a RegExp, watch out for double escaping your backslashes.
如果您要引用 RegExp,请注意双转义反斜杠。

