Out of my love for regular expressions comes this cool applet. It allows you to quickly test a regex before embedding it in your Java program.
Run the Java Regex Tester Applet now!
Behind the scenes
Most of the code for this application is Swing-related stuff. Probably the only interesting part is the one that deals with capturing regular expression groups. This snippet illustrates the process:
// simple email regex
String regex = "(?i)([A-Z0-9._%+-]+)@(([A-Z0-9.-]+)\\.([A-Z]{2,4}))";
String test = "spam@unindented.org";
// compile regex
Pattern pattern = Pattern.compile(regex);
// and match test string against it
Matcher matcher = pattern.matcher(test);
if (matcher.find())
{
StringBuffer capture = new StringBuffer();
do
{
// group zero always stands for the entire expression
capture.append(matcher.group(0) + "\n");
// remaining groups will be printed along with their index
for (int i = 1; i <= matcher.groupCount(); i++)
{
capture.append(i + ". " + matcher.group(i) + "\n");
}
capture.append("\n");
}
while (matcher.find());
// output results
System.out.println(capture.toString());
}
Which would output:
spam@unindented.org
1. spam
2. unindented.org
3. unindented
4. org
Check the java.util.regex.Pattern and java.util.regex.Matcher API specifications for in-depth information on regular expressions in Java.
And, of course, check out the source code for the Java Regex Tester Applet on GitHub!
Comments