RK Poddar RK Poddar - 1 year ago 102
Javascript Question

what is the difference between ?:, ?! and ?= in regex?

I searched for the meaning of these expressions but couldn't understand the exact differnce between them.
This is what they say:

  • ?:
    Match expression but do not capture it.

  • ?=
    Match a suffix but exclude it from capture.

  • ?!
    Match if suffix is absent.

I tried using these in simple RegEx and got similar results for all.
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]+)*

Answer Source

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".

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download