O'Reilly logo

Java Cookbook by Ian F. Darwin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Testing REs Interactively

Problem

You want to try out REs interactively before committing them to Java code.

Solution

Use the provided REDemo program.

Discussion

REDemo is a program in the org.apache.regexp package that lets you see the code that a RE compiles into, and also lets you watch it match interactively. You can change the RE or the string being matched easily, as it is a GUI application. Just give the command:

> java org.apache.regexp.REDemo

Figure 4-1 shows the program in action.

REDemo in action

Figure 4-1. REDemo in action

In the upper-right box you type the RE you want to test, and below that a test string to match it against. In the lower-left window, you see the compiled expression, and in the lower-right, you see what matched. $0 is the entire match, and $1 and up are tagged subexpressions that matched. Experiment to your heart’s content. When you have the RE the way you want it, you can paste it into your Java program. Remember to escape (backslash) any characters that are treated specially by Java and RE, such as the backslash itself, double quotes, \u, and others.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required