import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
final String regex = "^\\d(?=(?:-?\\d){7}-?\\d-\\d$)\\d*-\\d+-\\d*\\d-\\d$";
final String string = "01-234-5678-9\n"
+ "01234-56-78-9\n"
+ "0123-4-5678-9\n"
+ "012-345-678-9\n"
+ "01-234567-8-9\n"
+ "01-234-5678-9\n"
+ "0-12345-678-9\n"
+ "0-123-45678-9\n"
+ "0-123-45678-9\n"
+ "01-23456-78-9\n"
+ "0-123456-78-9\n"
+ "0-1234567-8-9\n"
+ "No Match:\n\n"
+ "01-234-56788-9\n"
+ "01-234-568-9\n"
+ "01--2345678-9\n"
+ "01-2345678--9\n"
+ "0-1-23456789\n"
+ "-01-2345678-9\n\n"
+ "0-1238787456-78-9\n"
+ "0-123456-78-3439\n"
+ "0-123456-738-9\n"
+ "30-123456-78-9";
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