3

What is difference between (?=regex) and (?:regex) in JavaScript?

Explain it with an example,Please.

PM 77-1
  • 12,933
  • 21
  • 68
  • 111
Ehsan
  • 12,655
  • 3
  • 25
  • 44
  • 4
    An explanation and example are provided for each by MDN under "[Special characters meaning in regular expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#Special_characters_meaning_in_regular_expressions)." – Jonathan Lonowski Dec 04 '16 at 03:18
  • 1
    http://www.rexegg.com/regex-disambiguation.html#lookarounds – PM 77-1 Dec 04 '16 at 03:21
  • 1
    You might also try Stack Overflow's Documentation on Regex – [Capture Groups](https://stackoverflow.com/documentation/regex/660/capture-groups), [Lookahead and Lookbehind](https://stackoverflow.com/documentation/regex/639/lookahead-and-lookbehind) – Jonathan Lonowski Dec 04 '16 at 03:22
  • This is the first result in Google, so it probably meets the users questionning – greg Jan 28 '17 at 18:02

1 Answers1

12

(?=regex) is a positive lookahead, it matches a group after the main expression without including it in the result.
Example:

\d(?=px)
1pt 2px 3em 4px

This will only match the 2 and the 4, not the entire 2px and 4px.

(?:regex) is a non-capturing group, it groups multiple tokens together without creating a capture group.
Example:

(?:ha)+
hahaha haa hah!

This will match each ha, but not create a group for it.

stelar7
  • 336
  • 1
  • 3
  • 14