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.

Get Java Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.