0

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.

4
  • Your requirements mean that a regex is not that necessary here. String.startsWith() + StringUtils.isNumeric + String.length() can be used. Commented Feb 16, 2016 at 9:26
  • @WiktorStribiżew can you explain why? Commented Feb 16, 2016 at 9:27
  • 1
    StringUtils requires an external library, and I see nothing wrong with using regex here. Commented Feb 16, 2016 at 9:31
  • NumberFormat.getInstance().parse(value) can be used instead of StringUtils.isNumeric. No one says a regex is a wrong way. Commented Feb 16, 2016 at 9:32

2 Answers 2

2

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}$");
Sign up to request clarification or add additional context in comments.

4 Comments

Why use 3 different patterns when you can use 1? And why do you think OP solution "counted" characters incorrectly? :)
This code is readable, and sometimes this is more valuable than having a slick looking (and non maintainable) regex.
@WiktorStribiżew His original patterns were matching the initial portion plus the entire length of what he wanted. To put it another way, in the first pattern he wants 11 characters total, but he was matching 11 characters after the initial pattern, for a total of 15 characters.
So, it is not patterns that are to blame, it is a logical error made by OP. And the problem is different in the second regex.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.