Regex Pattern for Mobile Number in Java 2024 - Java Technical Interview

 Regex Pattern for Mobile Number

    Here we are going to check whether the given String is contain mobile number or not using the Regex Pattern matching logic in Java. The steps are

Logical Theory :

  • Check for Length: Ensure the number has exactly 10 digits (or more if including a country code).
  • Check for Digits: Ensure that all characters are numeric.
  • Regex Pattern for Validation :

  • Regex: ^\d{10}$
  • Explanation:
    • ^ asserts the start of the string.
    • \d{10} matches exactly 10 digits.
    • $ asserts the end of the string.

  • Code :

    package com.dinatechy.challange;


    import java.util.regex.Matcher;

    import java.util.regex.Pattern;


    public class MobileNoPattern {

    public static void main(String[] args) {

    // Mobile number Pattern

    // length should be 10

    // must be digits

    String mobileNo = "9876543210";

    Pattern pattern = Pattern.compile("^\\d{10}$");

    // d refers to only digit's

    // 10 length

    Matcher matcher = pattern.matcher(mobileNo);

    if(matcher.matches())

    System.out.println("Matched");

    else

    System.out.println("Not Matched");

    }


    }

    Scenario 1 : Only digits with length 10.

    Input :

    9876543210

    Output :

    Matched


    Scenario 2 : Contains one character but length is 10.

    Input :

    987654d210

    Output :

    Not Matched


    Scenario 3 : Only digits but length is not 10

    Input :

    98765432100

    Output :

    Not Matched


    Follow us for more useful Java Interview Programs like this....

    Comments

    Popular posts from this blog

    Finding Second largest number in Array - Java - TCS - Technical Interview

    Checking Character only in String - Java 2024 - MNC - Technical Interview

    Object Class in Java | Article | Solution Maker - Blog