import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
final String regex = "A\\s+change\\s+to\\s+\n"
+ "(?:(?:sub)?headings?|tariff\\s+item)\n"
+ "\\s+\\d[0-9.]*\n"
+ "(?:\\s+through\\s+\\d[0-9.]*)?\n"
+ "\\s+from(?:(?:,?\\s+(?:sub)?headings?\\s+\\d[0-9.]*)+(?:\\s+or\\s+\\d[0-9.]*)*\\s+or)?\n"
+ "\\s+any\\s+other\\s+(?:heading|chapter)\\.";
final String string = "A change to headings 0101 through 0106 from any other chapter.\n"
+ "A change to subheadings 0712.20 through 0712.39 from any other chapter.\n"
+ "A change to heading 0903 from any other chapter.\n"
+ "A change to subheading 1806.20 from any other heading.\n"
+ "A change to subheading 1207.99 from any other chapter.\n"
+ "A change to heading 4302 from any other heading.\n"
+ "A change to subheading 4105.10 from heading 4102 or any other chapter.\n"
+ "A change to subheading 4105.30 from heading 4102, subheading 4105.10 or any other chapter.\n"
+ "A change to subheading 4106.21 from subheading 4103.10 or any other chapter.\n"
+ "A change to subheading 4106.22 from subheadings 4103.10 or 4106.21 or any other chapter.\n"
+ "A change to tariff item 7304.41.30 from subheading 7304.49 or any other chapter.";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE | Pattern.COMMENTS);
final Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
System.out.println("Full match: " + matcher.group(0));
for (int i = 1; i <= matcher.groupCount(); i++) {
System.out.println("Group " + i + ": " + matcher.group(i));
}
}
}
}
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Java, please visit: https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html