Testing Java Regular Expressions: A Useful Harness
Have added here the modified code of a test harness, RegexTestHarness.java, for exploring the regular expression constructs supported by Java RegEx API. The command to run this code is java RegexTestHarness; no command-line arguments are accepted. The application loops repeatedly, prompting the user for a regular expression and input string. Using this test harness is optional, but you may find it convenient for exploring the test cases discussed in the following pages.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class RegexTestHarness {
public static void main(String[] args) {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
while (true) {
try{
System.out.println("Enter your regex: ");
String regExStr = in.readLine();
Pattern pattern = Pattern.compile(regExStr);
System.out.println("\nEnter input string to search: ");
String inputStr = in.readLine();
Matcher matcher = pattern.matcher(inputStr);
boolean found = false;
while (matcher.find()) {
System.out.println("\nI found the text " + matcher.group()
+ " starting at index "
+ matcher.start() + " and ending at " + matcher.end());
found = true;
}
if (!found) {
System.out.println("\nNo match found.");
}
}
catch (Exception e) {
System.out.println("\nCaught an exception. Description: " + e.getMessage());
}
System.out.println("---------");
}
}
}
Source:
http://download.oracle.com/javase/tutorial/essential/regex/test_harness.html
About this entry
You’re currently reading “Testing Java Regular Expressions: A Useful Harness,” an entry on Singaram's Tech Musings
- Published:
- June 19, 2011 / 5:34 PM
- Category:
- Coding tips, Java
- Tags:
- Regular expression

2 Comments
Jump to comment form | comment rss [?] | trackback uri [?]