Programming Tips - Java: Use the Pattern and Matcher classes to extract text

Date: 2011jan25 Update: 2025oct14 Language: Java Q. Java: Use the Pattern and Matcher classes to extract text A. Here is a full example:
import java.util.regex.Matcher; import java.util.regex.Pattern; class Demo { // Need to escape backslashes from string static final Pattern pattern = Pattern.compile("(\\d+)\\s+(\\w+)\\s+(\\d+)"); // YYYY MMM DD static void doMatch(String dateIn) { Matcher matcher = pattern.matcher(dateIn); if (matcher.matches()) { // Do match and fill group()'s System.out.println("The date matches the pattern"); // group(0) is the entire match // groupCount() is the number of groups in the pattern // (even if the match fails) String year = matcher.group(1); // 1 is the first String mon = matcher.group(2); String mday = matcher.group(3); System.out.println("year=" + year + " month=" + mon + " mday=" + mday); } else { System.out.println("The date does not match the pattern"); } } public static final void main(String[] args) { doMatch("2036 Apr 13"); } }
Output:
The date matches the pattern year=2036 month=Apr mday=13