import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
final String regex = "[+]?(?<!\\d)(?<!\\d[ -])\n"
+ "(?:\n"
+ " ((\\d{1,2}[ -]?)?[(]?\\d{3}[)]?[ -]?)\n"
+ " (\\d(?:[ -]?\\d){3,6})\n"
+ ")(?![ -]?\\d)";
final String string = "Matches:\n"
+ "--------\n"
+ " 1234567 123 45 67 123-45-67 \n"
+ " 123456789012 12 345 678 9012 12-345-678-90-12 \n"
+ " 1 234 56 78 912 1 234 56 789 12 1 234 567 8 901 \n"
+ " +1234567 \n"
+ " +1234567890 +12-234 561 78 90 +12 234-561-78-90\n"
+ " +123456789012 \n"
+ " +1 234 561 78 90 \n"
+ " 1(234)567-89-01 \n"
+ " (495)1234567 (495) 123 45 67 \n"
+ " +33 (014)-020 53 17\n\n"
+ "Doesn't match: \n"
+ "--------------\n"
+ " +123456 -- to short\n"
+ " +1234567890123 -- too long\n"
+ " 123 4567890123 -- too long";
final Pattern pattern = Pattern.compile(regex, 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