Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the exclamation point in another StackOverflow posting involving telephone number REGEX?

Tags:

regex

In A comprehensive regex for phone number validation, the accepted answer has a number of comments. One of the comments, by @jcmcbeth, suggests the following simple regular expression to use to obtain the digits of the telephone number submitted by a user:

string.replace("[^\d+!x]", "")

Immediately following the comment with this suggested regular expression, another questioner asks why the !x part?, which is then answered in the next comment: The !x is there to keep any "x" character from getting stripped.

This makes sense to me, except for the exclamation point !. Looking at documentation for character classes in regular expressions, I do not see that the exclamation point is a special character, and it doesn't seem to me that the x requires a special character preceding it. Also, from the discussion in the linked question, I do not see any comment indicating that an exclamation point might be part of a telephone number (which would explain its inclusion in the negated character class).

Can someone please explain to me why the exclamation point is present? Thanks.

like image 778
Dan Nissenbaum Avatar asked Apr 26 '12 19:04

Dan Nissenbaum


People also ask

What does exclamation mean in regex?

! If an exclamation mark (!) occurs as the first character in a regular expression, all magic characters are treated as special characters. An exclamation mark is treated as a regular character if it occurs anywhere but at the very start of the regular expression.


1 Answers

You're absolutely right, the x is sufficient. ! just matches a literal !, inside a character class or out. The only place it has any special meaning is when it's part of negative lookahead or a negative lookbehind.

like image 93
Alan Moore Avatar answered Oct 14 '22 01:10

Alan Moore