Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 771
Teddy Avatar asked Aug 09 '10 22:08

Teddy


People also ask

How do you pass square brackets in regex?

You can omit the first backslash. [[\]] will match either bracket. In some regex dialects (e.g. grep) you can omit the backslash before the ] if you place it immediately after the [ (because an empty character class would never be useful): [][] .

How do you use brackets in regex?

Use square brackets ( [] ) to create a matching list that will match on any one of the characters in the list. Virtually all regular expression metacharacters lose their special meaning and are treated as regular characters when used within square brackets.

How do I match a number in regex?

To match any number from 0 to 9 we use \d in regex. It will match any single digit number from 0 to 9. \d means [0-9] or match any number from 0 to 9. Instead of writing 0123456789 the shorthand version is [0-9] where [] is used for character range.

What do square brackets mean in regex?

Square brackets ( “[ ]” ): Any expression within square brackets [ ] is a character set; if any one of the characters matches the search string, the regex will pass the test return true.


1 Answers

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];
}
like image 176
jmar777 Avatar answered Sep 22 '22 18:09

jmar777