Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What do the question marks like ?: and ?! mean in Javascript regexp? [duplicate]

Like the regexp in this one? What does it match?

document.getElementById("MyElement").className = 
   document.getElementById("MyElement").className.replace
  ( /(?:^|\s)MyClass(?!\S)/ , '' )
like image 693
trunpet Avatar asked Nov 17 '11 23:11

trunpet


People also ask

What is ?! Mean in RegExp?

It's a negative lookahead, which means that for the expression to match, the part within (?!...) must not match. In this case the regex matches http:// only when it is not followed by the current host name (roughly, see Thilo's comment). Follow this answer to receive notifications.

What does question mark mean in regex JavaScript?

A question mark ( ? ) immediately following a character means match zero or one instance of this character . This means that the regex Great!? will match Great or Great! .

What does question mark colon mean in regex?

The question mark and the colon after the opening parenthesis are the syntax that creates a non-capturing group. The regex Set(Value)? matches Set or SetValue. In the first case, the first (and only) capturing group remains empty. In the second case, the first capturing group matches Value.

How do you match a question mark in regex?

But if you want to search a question mark, you need to “escape” the regex interpretation of the question mark. You accomplish this by putting a backslash just before the quesetion mark, like this: \? If you want to match the period character, escape it by adding a backslash before it.


1 Answers

?: means make the capturing group a non capturing group, i.e. don't include its match as a back-reference. This is often done to increase performance and de-clutter the back-references when a capturing group is necessary to use the | operator.

In your example, it is being used to allow the or (|) of the start of the string ^ or whitespace (\s). Since the author of this code doesn't care about what it matched, they have made it a non capturing group.

?! is the negative lookahead. The regex will only match if the capturing group does not match.

In this example, the author wants to ensure the character after MyClass is not a whitespace character (\S).

It is somewhat possible the author of this code could have used word boundaries instead (\b).

like image 140
alex Avatar answered Oct 13 '22 09:10

alex