Java匹配電話號碼
如何在列表中匹配電話號碼?
解決方法
下麵的示例演示如何使用phone.matches(phoneNumberPattern) 方法在一個列表中匹配到電話號碼。
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 + " regex: " + phoneNumberPattern; if (retval) { msg = " MATCH: pattern:" + phone + " regex: " + phoneNumberPattern; } System.out.println(msg + " "); return retval; } }
結果
上麵的代碼示例將產生以下結果。
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}