Java regex example code to find all matches in a string 

Joined:
03/07/2011
Posts:
57

May 25, 2011 15:22:08    Last update: May 25, 2011 15:25:05
Use Matcher.find() to find the next regex match until all matches are exhausted.
import java.util.regex.*;

public class RegExFindAll {
    public static void main(String[] args) {
	String str = "You can use a Matcher to find all matches to a regular repression";

	// find all words starting with m or c, and ends with n or r or s. 
	// RegEx backslash should be escaped with an additional one.
	Pattern p = Pattern.compile("\\b(m|c)\\w*(n|r|s)\\b");
	Matcher m = p.matcher(str);
	while (m.find()) { // find next match
	    String match = m.group();
	    System.out.println(match);
	}

        // false because regex does not match the whole string
        System.out.println("Matches: " + m.matches());
    }
}


To get case insensitive match, use:
Pattern p = Pattern.compile("(?i)\\b(m|c)\\w*(n|r|s)\\b");
Share |
| Comment  | Tags