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.

Maksim Vi.
  • 9,107
  • 12
  • 59
  • 85
  • 1
    try escaping your curly-brackets. – drudge Nov 16 '10 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 `\{` – Maksim Vi. Nov 16 '10 at 23:47

3 Answers3

58

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

Yves M.
  • 29,855
  • 23
  • 108
  • 144
mike
  • 4,393
  • 1
  • 27
  • 16
  • 8
    Actually, looks like lookbehinds are officially part of the JS Regex spec (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#assertions), but only supported in Chromium as of posting (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#Browser_compatibility) – webbower Feb 19 '19 at 18:51
  • 1
    How can it be replaced and get the same behavior? – César Castro Aroche Mar 23 '22 at 14:04
11

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

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

Then extract the value captured in the group.

cdhowie
  • 158,093
  • 24
  • 286
  • 300
  • it extracts the whole thing, in my case I just need an integer. – Maksim Vi. Nov 16 '10 at 23:54
  • @negative: Notice the parentheses around the `\d+`; the integer is captured in group #1. – Alan Moore Nov 17 '10 at 00:37
  • @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'. – Maksim Vi. Nov 17 '10 at 00:56
5
var str = "some text{index:1}{id:2}{value:3}";
var index = str.match(/{index:(\d+)}/);
index = index && index[1]*1;
Phrogz
  • 296,393
  • 112
  • 651
  • 745