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) {
				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());


Source: http://download.oracle.com/javase/tutorial/essential/regex/test_harness.html



  1. […] Testing Java Regular Expressions: A Useful Harness (singztechmusings.wordpress.com) […]

  2. […] Testing Java Regular Expressions: A Useful Harness (singztechmusings.wordpress.com) […]

  3. Thank you Singaram this works perfectly in the latest Sprint Tools Suite STS as Oracles test harness does not work out of the box. Cheers!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: