Mobile Validation Using Java Regular Expression

We discussed here to validate Indian mobile number using concept of regular expression and Indian mobile numbering convention follows a
particular protocol

1.India mobile number contains 10 digits
2.First digit of any number is either 7,8,9 and rest 9 lies between 0-9
3.if we include country code then number will be either 11 or 12 digits
 a) In case of 11 digits First digit will be 0
 b) In case of 12 digits First two digits will be 91

So at first we design regular expression which follows above rules At first we write a rule which follow first number will be either 7,8 or 9 and for this we will write

[7,8,9] or in short we can write like this [7-9]

after that we have to write rest 9 digits between 0-9 and for this in case of regular expression we can write like this
[0-9][0-9].........[0-9] either [0-9] 9 times or in short [0-9]{9}

And when we want to write std code then in case of 11 digit i.e to write 0 and in case of 12 digits we write std code as 91 and to full fill this rule we use

(0|91)[7-9][0-9]{9}

And hence our complete regular expression will be

(0|91)?[7-9][0-9]{9}


import java.util.regex.*;
import java.util.*;
public class RegexExample1 {

    public static void main(String[] args) {
        String mobile;
        Scanner sb = new Scanner(System.in);
        Pattern p = Pattern.compile("(0|91)?[789][0-9]{9}");
        System.out.println("Enter your mobile number :");
        mobile = sb.next();
        Matcher m = p.matcher(mobile);
        if (m.find() && m.group().equals(mobile)) {
            System.out.println("Matcher is find");
        } else {
            System.out.println("Match is not find ");
        }

    }
}

                                                                                                        

Comments

Popular posts from this blog

Secure Database Connectivity in node.js with mysql

Export data from mysql db to csv file using java

API (Application Programming Interface)