FileDocCategorySizeDatePackage
REmatchTwoFields.javaAPI DocExample528Fri May 09 15:25:50 BST 2003None

REmatchTwoFields.java

import java.util.regex.*;

/*
 * Reverse the order of two fields.
 * Input:
 * Adams, John Quincy
 * Output:
 * John Quincy Adams
 */
public class REmatchTwoFields {
	public static void main(String[] args) {
		String inputLine = "Adams, John Quincy";
		// Construct an RE with parens to "grab" both field1 and field2
		Pattern r = Pattern.compile("(.*), (.*)");
		Matcher m = r.matcher(inputLine);
		if (!m.matches())
			throw new IllegalArgumentException("Bad input");
		System.out.println(m.group(2) + ' ' + m.group(1));
	}
}