0

I am learning Java regex and in below program for list[4] item I am expecting "Its a valid number : +11234562222" but it prints as invalid. I have made - optional in regex (\\+\\d{1,2}-?). Can anyone point out what is missing in this code ?

Current output

> Its a valid number : 123-456-2222
Its a valid number : +1-123-456-2222
Its a valid number : 1234562222
Its a invalid number : 12345622226
Its a invalid number : +11234562222

Expected output

> Its a valid number : 123-456-2222
Its a valid number : +1-123-456-2222
Its a valid number : 1234562222
Its a invalid number : 12345622226
Its a valid number : +11234562222

public static void vali_mobile_num(){

String mob_pat = "^(\\+\\d{1,2}-?)?+(\\d{3}-?){2}+\\d{4}$";
List list = new ArrayList();

list.add( "123-456-2222");
list.add("+1-123-456-2222");
list.add("1234562222");
list.add("12345622226");
list.add("+11234562222");

Pattern p = Pattern.compile(mob_pat);

list.forEach(x -> {
    Matcher m = p.matcher(x.toString());
    if(m.find()){
        System.out.println("Its a valid number : "+m.group());
    }
    else
        System.out.println("Its a invalid number : "+ x);   

});

}

user2895589
  • 1,010
  • 4
  • 20
  • 33
  • 1
    Have a look at your expression: the first optional group would match `+11`. Next you have 2 groups of 3 digits which might be followed by a minus characters. So those would match `234` and `562`. Finally you expect a group of 4 digits but the string only have `222` left. Why does `1234562222` match? Because the first optional group containing `\+` doesn't match, thus leaving `123`, `456` and `2222` for the other groups to match. – Thomas Jan 31 '19 at 16:16
  • 1
    You should adhere to the Java Naming Conventions: method names are written in camelCase, that means no underscores. E.g. `vali_mobile_num` should be `validateMobileNum`. – MC Emperor Jan 31 '19 at 16:21

1 Answers1

1

Your regex is almost fine except you have an extra + I don't understand why. Just remove that and it is good to go.

^(\\+\\d{1,2}-?)?+(\\d{3}-?){2}+\\d{4}$
                 ^ is not needed

Try this Java code,

List<String> list = Arrays.asList("123-456-2222","+1-123-456-2222","1234562222","12345622226","+11234562222");
Pattern p = Pattern.compile("^(\\+\\d{1,2}-?)?(\\d{3}-?){2}+\\d{4}$");

list.forEach(x -> {
    Matcher m = p.matcher(x);
    if(m.matches()) {
        System.out.println(x + " is Valid");
    } else {
        System.out.println(x + " is Invalid");
    }
});

Prints,

123-456-2222 is Valid
+1-123-456-2222 is Valid
1234562222 is Valid
12345622226 is Invalid
+11234562222 is Valid
Pushpesh Kumar Rajwanshi
  • 18,127
  • 2
  • 19
  • 36