Java中如何使用matches方法验证09DD-DDD-DD DD格式的字符串?
Fixing Your Java Phone Number Validation with
matches() Hey there! Let's work through why your current code isn't running correctly and fix it up to validate that "09DD-DDD-DD DD" format properly.
What's Wrong with Your Current Code?
You've got two key issues here:
- Incorrect regex escaping: In Java, to represent a digit in a regular expression, you need to use
\\d(two backslashes). Your code uses//d, which gets treated as literal characters/dinstead of matching digits—so the regex can never find a match. - Mismatched regex structure: Your regex
//d{4}-//d{3}-//d{2} //d{2}expects four digits at the start, but you're already checking that the first two characters are "09". This creates a conflict: you're essentially asking for "09" followed by four digits, which doesn't align with your target format of "09DD-DDD-DD DD".
Corrected Code (Recommended Approach)
The cleanest way to handle this is to let the regex handle the entire validation, including the "09" prefix. This removes redundant checks and ensures the full format is enforced:
public void setPhone(String p) { // Regex breakdown: // ^ = start of string // 09 = matches the required prefix // \\d{2} = matches two digits (DD) // - = matches the literal hyphen // \\d{3} = matches three digits (DDD) // - = matches another hyphen // \\d{2} = matches two digits (DD) // = matches the space // \\d{2} = matches the final two digits (DD) // $ = end of string (ensures no extra characters are present) if (p != null && p.matches("^09\\d{2}-\\d{3}-\\d{2} \\d{2}$")) { this.phone = p; } else { System.out.println("Phone number must start with 09 and follow the format: 09DD-DDD-DD DD"); } }
Alternative (Keeping Your Initial Prefix Check)
If you want to keep the charAt() check for the "09" prefix, you need to fix the regex and add a length check to avoid StringIndexOutOfBoundsException (if the input string is shorter than 2 characters):
public void setPhone(String p) { // First ensure the string is long enough, then check prefix, then validate format if (p != null && p.length() == 14 && p.charAt(0) == '0' && p.charAt(1) == '9' && p.matches("09\\d{2}-\\d{3}-\\d{2} \\d{2}")) { this.phone = p; } else { System.out.println("Phone number must start with 09 and follow the format: 09DD-DDD-DD DD"); } }
Key Notes
- Always add a null check for the input string
pto avoidNullPointerExceptionwhen calling methods likecharAt()ormatches(). - The
^and$anchors in the regex ensure that the entire string matches the format—no extra characters before or after will be allowed.
内容的提问来源于stack exchange,提问作者Mohadeseh
相关产品推荐
相关产品推荐

