Subject: New help with Pattern for special characters
Posted By: 2BOrNot2B Post Date: 7/2/2008 4:03:55 PM
Hi.

 I am currently working with Pattern and Matcher in Java.
 I have the following strings:

    Boys play balls. Girls play dolls.   Baby likes bottles.

 I like to create a pattern to find the period and space(s) in the string. This is my pattern so far, ".\\s+".  It doesn't work because the "." in my pattern could mean any character.

How do I make my pattern to recognize it as a period, and not any character.

Please help.

Reply By: Old Pedant Reply Date: 7/2/2008 4:17:36 PM
\.

Most special characters can be escaped by preceding them with a back slash.  (Which of course needs to be two slashes because Java treats the single one as its *own* escape.)

So, the pattern would be
      "\\.\\s+"

I tend to escape all special characters at all times, just for the paranoia of it.  Even when I don't have to.

For example, I'll tend to use
    "[a-z\\[\\-]"
even though I know in my head that no backslashes are needed there.  But guess what:  Most of the time my patterns work first time.  I'll take the extra typing in place of the extra debugging.

Go to topic 72467

Return to index page 1