Validate Phone Number

This program validates phone number using regex.

Problem Statement

Write a Java program to validate a phone number in format XXX-XXX-XXXX.

Source Code

1 public class RegexPhoneValidation {
2 public static void main(String[] args) {
3 System.out.println("Eduinq Regex Phone Validation");
4 String phone="123-456-7890";
5 String regex="^\\d{3}-\\d{3}-\\d{4}$";
6 if(phone.matches(regex)) System.out.println("Valid phone number");
7 else System.out.println("Invalid phone number");
8 }
9 }

Program Output

Eduinq Regex Phone Validation
Valid phone number

Explanation

The regex ^\d{3}-\d{3}-\d{4}$ requires exactly three digits, a hyphen, three digits, a hyphen, and four digits, and matches() validates the phone string against this fixed format.

Quick Links to Explore