24

I have the following regular expression:

/(?<={index:)\d+(?=})/g

I am trying to find index integer in strings like this one:

some text{index:1}{id:2}{value:3}

That expression works fine with php, but it doesn't work in javascript, I get the following error:

Uncaught SyntaxError: Invalid regular expression: /(?<={index:)\d+(?=})/: Invalid group

What do I need to fix?

Thanks.

2
  • 1
    try escaping your curly-brackets. Commented Nov 16, 2010 at 23:44
  • @jnpcl I just tried it a minute ago Uncaught SyntaxError: Invalid regular expression: /(?<=\{index:)\d+(?=\})/: Invalid group it doesn't work, unless there is another way to escape curly brackets other than \{ Commented Nov 16, 2010 at 23:47

3 Answers 3

59

(?<= ) is a positive lookbehind. JavaScript's flavor of RegEx does not support lookbehinds (but it does support lookaheads).

Sign up to request clarification or add additional context in comments.

3 Comments

Actually, looks like lookbehinds are officially part of the JS Regex spec (developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…), but only supported in Chromium as of posting (developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…)
How can it be replaced and get the same behavior?
If nothing else works, you could reverse the string, do a reversed regexp match with a positive lookahead and reverse the result. But that may not apply to your problem you're having.
11

JavaScript does not support look-behind assertions. Use this pattern instead:

/{index:(\d+)}/g

Then extract the value captured in the group.

3 Comments

it extracts the whole thing, in my case I just need an integer.
@negative: Notice the parentheses around the \d+; the integer is captured in group #1.
@Alan Moore, may be I am doing something wrong, but "some text{index:1}{id:2}{value:3}".match(/{index:(\d+)}/g)[0] returns {index:1} AND "some text{index:1}{id:2}{value:3}".match(/{index:(\d+)}/g)[1] returns 'undefined'.
5
var str = "some text{index:1}{id:2}{value:3}";
var index = str.match(/{index:(\d+)}/);
index = index && index[1]*1;

1 Comment

Ah, I see, no /g really helps =)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.