Jump to content
Larry Ullman's Book Forums

Recommended Posts

I'm in the middle of Chapter 14, Perl-compatible Regular Expressions.

 

On Page 444, the following pattern is offered to test for presence of non-whitespace characters in a string:

 

^\S$

 

If I'm interpreting the chapter correctly so far, in the form created for testing subjects against patterns, pcre.php, I should enter this code inside a pair of delimeters, like so:

 

/^\S$/

 

So, I've done that, and typed a string into the subject text area:

 

Testing for whitespace characters.

 

I received FALSE, so far so good.

 

Then I type simply:

 

testing

 

And I received FALSE again!

 

Suspecting that I may have messed up the code of pcre.php, I replaced my file with the one I downloaded from Larry's website. Ran the same two tests again, received same results.

 

Either I'm missing something, which I suspect is the case, or the pattern is incorrect.

 

Could someone please explain to me how to make it work or what I'm doing wrong?

Link to comment
Share on other sites

Thanks, HartleySan - but do you mind if I ask for a little more detailed explanation?

 

First, I want to understand exactly what is this expression testing for. The presence of a single white space in the string, am I right?

 

So, if I test something like: 'test string' against this pattern, it should return TRUE, correct?

 

Or am I misunderstanding this?

Link to comment
Share on other sites

\s matches any whitespace character and \S matches any non-whitespace character, so ^\S$ matches a single non-whitespace character: a string that both begins and ends with \S. If you were to change it to ^\S+$, that would match one or more non-whitespace characters, meaning that "string" would be fine but "test string" would not.

  • Upvote 1
Link to comment
Share on other sites

Hi Larry!

 

So, from your explanation I deduce that the queries that the pattern in question is describing a string that begins with a single non-whitespace character and ends immediately after that character.

 

So these strings should match the pattern: 'a', 'b', 'c', '-', '1', '`' --

 

-- and these shouldn't: 'aa', '2012', ' ', 'and so on'.

 

Did I get this right?

Link to comment
Share on other sites

 Share

×
×
  • Create New...