Check out Scrivo

Do you want to try out Scrivo? Then here's a demo for you that does not just get your feet wet but lets you plunge right in.

Contact us

For more information, please contact us. We're happy to help you out!

Next Oct 22 Previous

Not finding is harder than finding

You want to test if a string doesn't contain (some) white space. Which regular expression will you use:

A: "/[^\s]/"
B: "/[^\s]*/"
C: "/^[^\s]*/"
D: "/^[^\s]*$/"


Let's kick this one off with a quote by Bertrand Russel:

Suppose you are told 'there is butter in the larder, but no cheese'. Although they seem equally based upon sensible experience in the larder , the two statements 'there is butter' and 'there is not cheese' are really on a very different level.

And Inquiry into Meaning and Truth: Object Language, 1940.

Now back to the question, what do these regular expressions do:

A: "/[^\s]/"

This one tests if the string contains at least one no-whitespace character. So a string like " a" will match.
B: "/[^\s]*/"

Here any sequence of zero or more no-whitespace characters will cause a match so any string even " " will yield a match.
C: "/^[^\s]*/"

Much like B but the sequence of zero or more no-whitespace characters need to be at the beginning of the line. Again any string matches.
D: "/^[^\s]*$/"

This is the correct answer. From the start to the end end of the string all characters need to be no-whitespace characters.

To positively affirm that there are no spaces in a string you have to judge each character in the string for what it's not. That's really different and more difficult than judging characters for what the are. To say it in code:

preg_match("/^[^\s]*$/", $str) === !preg_match("/\s/", $str)