Java Reference
In-Depth Information
REMEMBER THIS!
Remember that because a regex compiles strings that are also compiled by javac , you usually
need two levels of escaping for any special characters, including backslash, double quotes, and so
on. For example, the regex:
"You said it\."
has to be typed like this to be a valid compile-time Java language String :
"\"You said it\\.\""
I can't tell you how many times I've made the mistake of forgetting the extra backslash in \d+ ,
\w+ , and their kin!
In Figure 4-1 , I typed qu into the REDemo program's Pattern box, which is a syntactically val-
id regex pattern: any ordinary characters stand as regexes for themselves, so this looks for
the letter q followed by u . In the top version, I typed only a q into the string, which is not
matched. In the second, I have typed quack and the q of a second quack . Because I have se-
lected Find All, the count shows one match. As soon as I type the second u , the count is up-
dated to two, as shown in the third version.
Regexes can do far more than just character matching. For example, the two-character regex
^T would match beginning of line ( ^ ) immediately followed by a capital T—that is, any line
beginning with a capital T. It doesn't matter whether the line begins with Tiny trumpets , Tit-
anic tubas , or Triumphant twisted trombones , as long as the capital T is present in the first
position.
But here we're not very far ahead. Have we really invested all this effort in regex technology
just to be able to do what we could already do with the java.lang.String method
startsWith() ? Hmmm, I can hear some of you getting a bit restless. Stay in your seats!
What if you wanted to match not only a letter T in the first position, but also a vowel (a, e, i,
o, or u) immediately after it, followed by any number of letters in a word, followed by an ex-
clamation point? Surely you could do this in Java by checking startsWith("T") and
charAt(1) == 'a' || charAt(1) == 'e' , and so on? Yes, but by the time you did that,
you'd have written a lot of very highly specialized code that you couldn't use in any other
Search WWH ::




Custom Search