简体   繁体   中英

Java regex check if certain characters match pattern

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.

Your patterns were counting characters incorrectly. Use this:

static Pattern p1 = Pattern.compile("^0937[0-9]{7}$");
static Pattern p2 = Pattern.compile("^937[0-9]{7}$");
static Pattern p3 = Pattern.compile("^63937[0-9]{7}$");

I think you can use only one pattern, something like this:

static Pattern p = Pattern.compile("^((0937)|(937)|(63937))[0-9]{7}$");

This patter include your three cases with the correct length. So if you can have a maintable regex, I recommend you to use a properties file.

I hope this information helps you.

Good luck.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM