Java Match Phone Numbers Using Regular Expression

Chapter: Regular Expression Last Updated: 11-09-2016 11:55:20 UTC

Program:

            /* ............... START ............... */
                
public class JavaMatchPhoneNumbers {

	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;
	}
}
                /* ............... END ............... */
        

Output

 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}

 MATCH: pattern:585-4009
 regex: (\d-)?(\d{3}-)?\d{3}-\d{4}

NO MATCH: pattern:1.999-585-4009
 regex: (\d-)?(\d{3}-)?\d{3}-\d{4}

NO MATCH: pattern:999 585-4009
 regex: (\d-)?(\d{3}-)?\d{3}-\d{4}

NO MATCH: pattern:1 585 4009
 regex: (\d-)?(\d{3}-)?\d{3}-\d{4}

NO MATCH: pattern:111-Java2s
 regex: (\d-)?(\d{3}-)?\d{3}-\d{4}

Tags

Java Match Phone Numbers Using Regular Expression

Similar Programs Chapter Last Updated
Java Regular Expression Match Single Digit Regular Expression 15-12-2016
Java Regular Expression To Check Number With Dot Separator And Two Decimal Regular Expression 14-12-2016
Java Regular Expression To Check Numeric Regular Expression 14-12-2016
Java Regular Expression Digit Only Regular Expression 14-12-2016
Java Check Date Format Example Regular Expression 14-09-2016
Java Validate email Address Regular Expression 13-09-2016
Java Replace All Occourances Of String Example Regular Expression 13-09-2016
Java Make First Letter Of Each Word In Uppercase Regular Expression 13-09-2016
Java Last Index Of Word Using Regular Expression Regular Expression 11-09-2016
Java Find Word Occurrence Using Regular Expression Regular Expression 11-09-2016
Java Splitting String Using Regular Expression Regular Expression 11-09-2016
Java Regex Pattern Split Example Regular Expression 21-06-2016
IP Address From String In Java Regex Regular Expression 21-07-2016
Validate UserName Using Regular Expression In Java Regular Expression 22-09-2018
Java Regex IP Address Example Regular Expression 21-07-2016
Regular Expression In Java Example Regular Expression 09-07-2016
Pattern Matching In Java Example Regular Expression 09-07-2016

1