java

Phone number validation using regular expression (regex) in Java

In this tutorial, we are going to see how to validate a phone number using regular expressions (regex) and the Pattern.compile(regex) method to compile the regular expressions in Java.
 

How to validate a phone number using regular expressions (regex) in Java:
import java.util.*;
import java.util.regex.*;

public class Main {
   public static void main(String[] args) {
      
      ArrayList<String> tels = new ArrayList<String>();
      tels.add("01 23 45 67 89");
      tels.add("01.23.45.67.89");
      tels.add("01-23-45-67-89");
      tels.add("+33 1 23 45 67 89");
      tels.add("+33123456789");

      String regex = "^(?:(?:\\+|00)33|0)\\s*[1-9](?:[\\s.-]*\\d{2}){4}$";
      
      Pattern pattern = Pattern.compile(regex);

      for(String tel : tels)
      {
          Matcher matcher = pattern.matcher(tel);
          System.out.println(tel +" : "+ matcher.matches());
      }
   }
}

Output:

01 23 45 67 89 : true
01.23.45.67.89 : true
01-23-45-67-89 : true
+33 1 23 45 67 89 : true
+33123456789 : true
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *