Arvind Gangwar
Arvind Gangwar

Reputation: 153

Regex for mobile number with optional country code

actually i am using it at internal application which generate a xml, whose code is written in java. But here at application if ^(249)?1\d{8}$ then it forward to next operation, if number not above then give user wrong input i.e. I am not directly interact to java codeI want a regex for mobile number validation. The regex pattern should be such that it must accept 249 country code(only once) followed by '1' (only once) followed by 8 digit. Country code should be optional.If country code doesn't exist, it should accept only 9 digit number which started with 1.

Also Regex which negate above condition, means any mobile number which not start with 249 and having length 12, if it of length 9 and not start with 1. The regex should accept numbers like

249189372837 start with 249 followed by 1 and must of 12 digit length
249123476358 
183526352  if start with 1 and must of 9 digit length (249 optional) 

Should not accept

2431983645238   country code not 249
24924356383799  more then 12 digit including country code
249212236472 not 1 after 249
1232345678   more length then 9
12345323     less length then 9
456278399    if 249 is not there then mut start with 1 with length of 9

So I need regex for accepting above condition and one regex which accept any number other then above accepting condition.

I tried this ^(249)([1]{1})([0-9]{8})$ when start with 249 then (1) then 8 digits and ^(1)([0-9]{8})$ when number start with 1 followed by 8 digit, but I require one regex for both condition.

actually i am using it at internal application which generate a xml, whose code is written in java. But here at application if ^(249)?1\d{8}$ (answered by @rock321987) then it forward to next operation, if number not above regex then give user wrong input i.e. I am not directly interact to java code

Lots of thanks in advance for any help and suggestion.

Upvotes: 1

Views: 2751

Answers (1)

rock321987
rock321987

Reputation: 11042

This regex will work

^(249)?1\d{8}$

Regex Demo

For second part

(?=^1)(^\d{1,8}$|^\d{10,}$)|(?=^2491)(^\d{1,11}$|^\d{13,}$)
(?!^(2491|1))^(\d{9}|\d{12})$

Java Code

Scanner x = new Scanner(System.in);
String pattern = "^(249)?1\\d{8}$";
Pattern r = Pattern.compile(pattern);
while (true) {
    String line = x.nextLine();
    Matcher m = r.matcher(line);
    if (m.find()) {
         System.out.println("Found -> " + m.group());
    } else {
         System.out.println("Not Found");
    }
}

Ideone Demo

Upvotes: 2

Related Questions