I need your help with regex. This is my requirement, check string if it starts with 0937, 937 or 63937. Next check if string ONLY contains digits and check if length of characters for 0937 = 11, 937 = 10, 63937 = 12.
So far this is what I've tried:
class MyRegex {
static Pattern p1 = Pattern.compile("^0937[0-9]{11}+$");
static Pattern p2 = Pattern.compile("^937[0-9]+{10}$");
static Pattern p3 = Pattern.compile("^63937[0-9]{12}$");
public static void main(String []args){
String phone = "09375126435"; //"639375126439"; // "9375126435";
System.out.println(validateABSMobileNumber(phone));
}
public static boolean validateABSMobileNumber(String phone){
return p1.matcher(phone).matches() || p2.matcher(phone).matches() || p3.matcher(phone).matches() ;
}
}
Sample test cases:
09375126435 = true 0937512643 = false 639375126439 = true 63937512643 = false 9375126439 = true 937512643 = false
But it doesn't run correctly. Any ideas how to fix this? Thanks.
String.startsWith()+StringUtils.isNumeric+String.length()can be used.StringUtilsrequires an external library, and I see nothing wrong with using regex here.NumberFormat.getInstance().parse(value)can be used instead ofStringUtils.isNumeric. No one says a regex is a wrong way.