Search code examples
javascriptregex

Difference between ?:, ?! and ?=


I searched for the meaning of these expressions but couldn't understand the exact difference between them.

This is what they say:

  • ?: Match expression but do not capture it.
  • ?= Match a suffix but exclude it from capture.
  • ?! Match if the suffix is absent.

I tried using these in simple RegEx and got similar results for all.

For example: the following 3 expressions give very similar results.

  • [a-zA-Z0-9._-]+@[a-zA-Z0-9-]+(?!\.[a-zA-Z0-9]+)*
  • [a-zA-Z0-9._-]+@[a-zA-Z0-9-]+(?=\.[a-zA-Z0-9]+)*
  • [a-zA-Z0-9._-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9]+)*

Solution

  • The difference between ?= and ?! is that the former requires the given expression to match and the latter requires it to not match. For example a(?=b) will match the "a" in "ab", but not the "a" in "ac". Whereas a(?!b) will match the "a" in "ac", but not the "a" in "ab".

    The difference between ?: and ?= is that ?= excludes the expression from the entire match while ?: just doesn't create a capturing group. So for example a(?:b) will match the "ab" in "abc", while a(?=b) will only match the "a" in "abc". a(b) would match the "ab" in "abc" and create a capture containing the "b".