Programming Tips - Java: Grab all occurances of a pattern in a String

Date: 2012sep21 Update: 2025sep24 Language: Java Q. Java: Grab all occurances of a pattern in a String A. Do group(1) while find() gets hits. As shown in this full example:
import java.util.regex.Pattern; import java.util.regex.Matcher; class Demo { // This pattern will find all Capitalized words static Pattern pat = Pattern.compile("([A-Z]\\w+)"); public static void main(String []args) { String mySubjectString = "Once Upon a time"; Matcher matcher = pat.matcher(mySubjectString); while (matcher.find()) { String hitWord = matcher.group(1); System.out.println("hit=" + hitWord); } } }
Output:
hit=Once hit=Upon