retrieve all occurrences of matched substring of a pattern. One match occurrence may contains several groups.
package egtry.regex;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MultipleMatch {
public static void main(String[] args) {
String text="john.smith@gmail.com\nuser.name@domain.com";
Pattern pat=Pattern.compile("(\\w+)");
int offset=0;
Matcher m=pat.matcher(text);
while(!m.hitEnd()) {
if (m.find(offset)) {
int n=m.groupCount();
System.out.println("matched word: "+m.group(1));
}
offset=m.end();
}
}
}
output
matched word: john
matched word: smith
matched word: gmail
matched word: com
matched word: user
matched word: name
matched word: domain
matched word: com