How REs Work in Practice
Problem
You want to know how these metacharacters work in practice.
Solution
Wherein I give a few more examples for the benefit of those who have not been exposed to REs.
In building patterns, you can use any combination of ordinary text and the metacharacters or special characters in Chapter 4. For example, the two-character RE ^T would match beginning of line (^) immediately followed by a capital T, i.e., any line beginning with a capital T. It doesn’t matter whether the line begins with Tiny trumpets, or Titanic tubas, or Triumphant 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 RE 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 exclamation 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 application. With regular expressions, you can just give the pattern ^T[aeiou]\w*. That is, ^ and T as before, followed by a character classlisting the vowels, ...