- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Phone Number validation using Java Regular Expressions
The phone number can be validated using the java.util.regex.Pattern.matches() method. This method matches the regular expression for the phone number and the given input phone number and returns true if they match and false otherwise.
Note: We are considering a demo number for our example since we cannot use our phone number publicly.
A program that demonstrates this is given as follows:
Example
public class Demo { public static void main(String args[]) { String phoneNumber = "9999999998"; String regex = "(0/91)?[7-9][0-9]{9}"; System.out.println("The phone number is: " + phoneNumber); System.out.println("Is the above phone number valid? " + phoneNumber.matches(regex)); } }
Output
The phone number is: 9999999998 Is the above phone number valid? True
Now let us understand the above program.
The phone number is printed. The Pattern.matches() method matches the regular expression for the phone number and the given input phone number and the result is printed. A code snippet which demonstrates this is as follows:
String phoneNumber = "9999999998"; String regex = "(0/91)?[7-9][0-9]{9}"; System.out.println("The phone number is: " + phoneNumber); System.out.println("Is the above phone number valid? " + phoneNumber.matches(regex));
- Related Articles
- Date validation using Java Regular Expressions
- Name validation using Java Regular Expressions
- Zip Code validation using Java Regular Expressions
- Validate Phone with Java Regular Expressions
- Program to check valid mobile number using Java regular expressions
- Java Regular Expressions Tutorial
- Email & Phone Validation in Swift
- Java regular expressions sample examples
- Possessive quantifiers Java Regular expressions
- Java Regular expressions Logical operators
- Reluctant quantifiers Java Regular expressions
- How to validate an email address using Java regular expressions.
- Checking for valid email address using regular expressions in Java
- Greedy quantifiers Java Regular expressions in java.
- How to Apply Data Validation to Force Phone Number Format in Excel?

Advertisements