import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
final String regex = "^(\\d|\\+|\\(|)\n"
+ "(\\d+|xx)\n"
+ "(xx|.)?\n"
+ "(\\d+|.)?\n"
+ "(\\))?\n"
+ "(\\d)?\n"
+ "(\\d|.)?\n"
+ "(\\))?\n"
+ ".+";
final String string = "9876-5432\n"
+ "98765-4321\n"
+ "11 9876-5432\n"
+ "011 9876-5432\n"
+ "0xx11 9876-5432\n"
+ "0xx 11 9876-5432\n"
+ "+55 11 9876-5432\n"
+ "+55 11 98765-4321\n"
+ "+551198765432\n"
+ "+5511987654321\n"
+ "(11)9876-5432\n"
+ "(11) 9876-5432\n"
+ "(0xx11) 9876-5432\n"
+ "+55 (11) 98765-4321";
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