简体   繁体   中英

How do I match a number inside square brackets with regex

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

Does JavaScript not support lookahead or lookbehind?

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]; }

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

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'

如果您要引用 RegExp,请注意双转义反斜杠。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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