- Java Programming Examples
- Example - Home
- Example - Environment
- Example - Strings
- Example - Arrays
- Example - Date & Time
- Example - Methods
- Example - Files
- Example - Directories
- Example - Exceptions
- Example - Data Structure
- Example - Collections
- Example - Networking
- Example - Threading
- Example - Applets
- Example - Simple GUI
- Example - JDBC
- Example - Regular Exp
- Example - Apache PDF Box
- Example - Apache POI PPT
- Example - Apache POI Excel
- Example - Apache POI Word
- Example - OpenCV
- Example - Apache Tika
- Example - iText
- Java Tutorial
- Java - Tutorial
- Java Useful Resources
- Java - Quick Guide
- Java - Useful Resources
How to match phone numbers in a list using Java
Problem Description
How to match phone numbers in a list?
Solution
Following example shows how to match phone numbers in a list to a particle pattern by using phone.matches(phoneNumberPattern) method.
public class MatchPhoneNumber { public static void main(String args[]) { isPhoneValid("1-999-585-4009"); isPhoneValid("999-585-4009"); isPhoneValid("1-585-4009"); isPhoneValid("585-4009"); isPhoneValid("1.999-585-4009"); isPhoneValid("999 585-4009"); isPhoneValid("1 585 4009"); isPhoneValid("111-Java2s"); } public static boolean isPhoneValid(String phone) { boolean retval = false; String phoneNumberPattern = "(\\d-)?(\\d{3}-)?\\d{3}-\\d{4}"; retval = phone.matches(phoneNumberPattern); String msg = "NO MATCH: pattern:" + phone + "\r\n regex: " + phoneNumberPattern; if (retval) { msg = " MATCH: pattern:" + phone + "\r\n regex: " + phoneNumberPattern; } System.out.println(msg + "\r\n"); return retval; } }
Result
The above code sample will produce the following result.
MATCH: pattern:1-999-585-4009 regex: (\\d-)?(\\d{3}-)?\\d{3}-\\d{4} MATCH: pattern:999-585-4009 regex: (\\d-)?(\\d{3}-)?\\d{3}-\\d{4} MATCH: pattern:1-585-4009 regex: (\\d-)?(\\d{3}-)?\\d{3}-\\d{4} NOMATCH: pattern:1.999-585-4009 regex: (\\d-)?(\\d{3}-)?\\d{3}-\\d{4} NOMATCH: pattern:999 585-4009 regex: (\\d-)?(\\d{3}-)?\\d{3}-\\d{4} NOMATCH: pattern:1 585 4009 regex: (\\d-)?(\\d{3}-)?\\d{3}-\\d{4} NOMATCH: pattern:111-Java2s regex: (\\d-)?(\\d{3}-)?\\d{3}-\\d{4}
The following is an example to verify phone number.
public class Main { private static boolean isValid(String s) { String regex = "\\d{2}-\\d{4}-\\d{6}"; return s.matches(regex); } public static void main(String[] args) { System.out.println(isValid("91-9652-018244")); } }
The above code sample will produce the following result.
true
java_regular_exp.htm
Advertisements
To Continue Learning Please Login
Login with Google