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?
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): [][] .
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.
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.
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.
This should work:
var regex = /\[[0-9]+\]/;
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];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With