import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
final String regex = "^(\\+){0,1}(254){0,1}(70|71|72|79)(\\d{7})|(254){0,3}(740|741|742|743|745|746|748|757|758|759|768|769|110|111)(\\d{6})$";
final String string = "VALID NUMBERS\n"
+ "254715228228\n"
+ "254722228228\n"
+ "254729228228\n"
+ "254745229228\n"
+ "254769229228\n"
+ "254110229228\n"
+ "254111229228\n\n"
+ "INVALID NUMBERS\n"
+ "254730229228\n"
+ "254744229228\n"
+ "254747229228\n"
+ "254760229228\n"
+ "254100229228\n\n\n"
+ "Sources: https://ca.go.ke/wp-content/uploads/2020/01/Telecommunication-Numbering-Plan-for-Kenya-Feb-2020-compressed.pdf\n\n\n";
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