Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression with exclamation marks on both sides ('!\d!')

Tags:

regex

php

I've seen the regular expression '!\d!' inside the PHP preg_match function. What the heck is this?

like image 578
Graduate Avatar asked Sep 25 '12 09:09

Graduate


People also ask

What does exclamation mark do in regex?

Search without case sensitivity. 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.

What does 2 exclamation marks mean in a text?

This punctation emoji of a double exclamation mark features two big red exclamation points that can be used to express surprise, shock, or to really emphasize or drive home a point.

Can we use exclamation mark after name?

This is totally fine if your name is P! nk or Yahoo! or Westward Ho! But if you're a normal human being, adding exclamation marks after your name will make you seem incredibly needy. Mr Forsyth said: 'The words, the content, should do the work.


2 Answers

From the PHP PCRE docs:

When using the PCRE functions, it is required that the pattern is enclosed by delimiters. A delimiter can be any non-alphanumeric, non-backslash, non-whitespace character.

In this case, it's simply using ! as the delimiter. Often it's used if you want to use the normal delimiter within the regex itself without having to escape it. Not really necessary in this case since the rest of the regex is simply \d, but it comes in handy for things like checking that a path contains more than three directory levels. You can use either of:

/\/.*\/.*\/.*\/ blah blah blah /

or:

!/.*/.*/.*/ blah blah blah !

Now they haven't been tested thoroughly, and may not work entirely as advertised, but you should get the general idea re the minimal escaping required.

Another example (from the page linked to above) is checking if a string starts with the http:// marker. Either of these two:

/^http:\/\//
!^http://!

would suffice, but the second is easier to understand.

like image 197
paxdiablo Avatar answered Sep 21 '22 08:09

paxdiablo


! is used as delimiter, \d matches the single digit.

It is the same as /[0-9]/

like image 45
xdazz Avatar answered Sep 22 '22 08:09

xdazz