18

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

2
  • 8
    What's with the downvotes? It could be worded better, but I think this is a reasonable question. Searching for punctuation is basically impossible and it's three clicks from the preg_match doc page to the PCRE regex delimiters doc page. And you have to know you are looking for "regex delimiter", but then you already know the answer... Sep 25, 2012 at 9:32
  • I've been coding PHP for years and I'd never seen ! used as a delimeter! I Googled and found this very helpful question. P.S. I suspect it's not used as a delimiter because it makes for less readable code. At first glance I interpreted the exclaimation mark to mean "Not" or "Negative match", I reckon many others do too so they avoid it in favour of readability. Jul 13, 2016 at 10:17

2 Answers 2

20

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.

0
6

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

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

1
  • 1
    Thanks, I thought that you always have to use the character "/". I didn't know that I can substitute it.
    – mosceo
    Sep 25, 2012 at 9:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.