import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
final String regex = "^(?!.*(?: |^)(?:\\+\\d|0)(?:[()-]*\\d){6,}(?!\\S)).*";
final String string = "abcd1234567\n\n"
+ "1234567\n"
+ "123-4567\n"
+ "02221234567\n"
+ "0222-1234567\n"
+ "+862221234567\n"
+ "+86-222-123-4567\n"
+ "+86(222)1234567\n"
+ "86-222-1234567\n\n"
+ "r 1234567 er \n"
+ " e 123-4567 e\n"
+ "ewq 02221234567 qw\n"
+ "2312 0222-1234567 232\n"
+ "we +862221234567 23\n"
+ "231 +86-222-123-4567 ewe\n"
+ ",,,, +86(222)1234567 sss\n"
+ "ff 86-222-1234567 dd\n\n"
+ "Some string here with no phone number\n\n"
+ "a number with 7 and more digits is input\n"
+ "and it starts with 0 or + symbols\n"
+ "and could contain optional symbols \"-\", \"(\" and \")\"\n"
+ "also enforce whitespace boundaries";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
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