views:

57

answers:

3

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?

+1  A: 

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

Andy E
A: 

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

spender
+6  A: 

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];
}
jmar777
This matches the number including the brackets, which is not what the OP wants. It's a decent alternative with groups, though.
strager
Good point - updated.
jmar777
Thanks for the work-around. Slightly kludgeish but oh well.
Teddy
@Teddy: Nothing kludgy about it; for this kind of job, a capture group should be the *first* tool you reach for.
Alan Moore
@Alan: Agreed - it requires an extra line or so of procedural code to retrieve the value, but it does so with minimal backtracking in the expression, so it's a fairly optimal solution by my (limited) regex foo.@Teddy: Thanks for the accept!
jmar777