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.
! 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With