0

The following javascript expression yields ["myParameter=foobar", "foobar"].

'XXXXmyParameter=foobar'.match(/(?:myParameter=)([A-Za-z]+)/);

Why is "myParameter=foobar" even a match? I thought that positive lookbehinds are excluded from matches?

Is there a way to only capture the ([A-Za-z]+) portion of my regex in javascript? I could just take the second item in the list, but is there a way to explicitly exclude myParameter= from matches in the regex?

John Hoffman
  • 17,857
  • 20
  • 58
  • 81
  • 1
    That's not a lookbehind, it's a non-capturing group. – Evan Davis Jan 09 '15 at 23:10
  • 1
    [JavaScript regular expressions do not support lookbehinds.](http://stackoverflow.com/a/3569116/1960455) – t.niese Jan 09 '15 at 23:10
  • No lookbehind in JS. If it did support it, would be ` /(?<=myParameter=)([A-Za-z]+)/`. JS has a deficient regex engine, should be fixed. –  Jan 09 '15 at 23:13

3 Answers3

3

(?:myParameter=) is a non-capturing group, not a lookbehind. JavaScript does not support lookbehinds.

The first element of the result is always the complete match. The value of your capture group is the second element of the array, "foobar".

If you used a capture group, i.e. (myParameter=), the result would be:

["myParameter=foobar", "myParameter=", "foobar"]

So again, the first element is the complete match, every other element corresponds to a capture group.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
2

You are not implementing Positive Lookbehind, (?:...) syntax is called a non-capturing group which is used to group expressions, not capture them (usually used in alternation when you have a set of different patterns).

You can simply reference the captured group for the match result.

var r = 'XXXXmyParameter=foobar'.match(/myParameter=([A-Za-z]+)/)[1];
if (r)
    console.log(r); //=> "foobar"

Note: Lookbehind assertions are not supported in JavaScript ...

hwnd
  • 69,796
  • 4
  • 95
  • 132
1

The myParameter is a match because you are using a non capturing group.

The non capturing group matches the text but it cannot be backreferenced.

Non Capturing Group:

(?:myParameter=)

Positive Lookahead:

(?=myParameter=)

Negative Lookahead:

(?!myParameter=)

The regex you need is:

(?!myParameter=)[A-Za-z]+$

DEMO

Andie2302
  • 4,825
  • 4
  • 24
  • 43
  • `(?!myParameter=)[A-Za-z]+` won't do what you think it will do. The engine will advance one position to make the assertion pass. So it would match "m`yParameter`" –  Jan 09 '15 at 23:41