Skip to Main Content
Java Cookbook
book

Java Cookbook

by Ian F. Darwin
June 2001
Intermediate to advanced content levelIntermediate to advanced
888 pages
21h 1m
English
O'Reilly Media, Inc.
Content preview from Java Cookbook

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, ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Practical Cloud-Native Java Development with MicroProfile

Practical Cloud-Native Java Development with MicroProfile

Emily Jiang, Andrew McCright, John Alcorn, David Chan, Alasdair Nottingham
Distributed Computing in Java 9

Distributed Computing in Java 9

Raja Malleswara Rao Malleswara Rao Pattamsetti

Publisher Resources

ISBN: 0596001703Supplemental ContentCatalog PageErrata