Java正则表达式去除邮编中含连字符的末尾四位数字无效问题
Hey there! I see you're trying to strip the last four digits (including the hyphen) from 9-digit ZIP codes like 94107-1532, but your current regex isn't doing the trick. Let's break down what's wrong and fix it up.
Why Your Current Regex Fails
Your regex -\d$ only matches a hyphen followed by one single digit at the very end of the string. Since your ZIP code suffix is four digits (like -1532), this pattern can't possibly match the full suffix—so it does nothing at all!
Solution 1: Correct Regex Pattern
To target the hyphen plus exactly four digits at the end of the string, use this adjusted regex instead:
public static String removeRoute(String zipCode) { return zipCode.replaceAll("-\d{4}$", ""); }
-\d{4}: Matches a hyphen followed by exactly 4 digits$: Ensures this pattern is at the end of the string, so we don't accidentally match hyphens elsewhere (though valid ZIP codes shouldn't have other hyphens!)
Testing this with your sample ZIP codes:
94107-1532→9410794107-1535→9410794107-1511→94107
Solution 2: No Regex Needed (Simpler for Standard ZIP Codes)
If you're certain all your input ZIP codes follow the standard XXXXX-XXXX format, you can skip regex entirely and just grab the first 5 characters:
public static String removeRoute(String zipCode) { // Add a check to avoid index out of bounds if input is invalid if (zipCode != null && zipCode.length() >= 5) { return zipCode.substring(0, 5); } return zipCode; // Return original if it's not a valid 9-digit ZIP }
This is often faster and easier to read for straightforward cases like this.
Bonus: Handling Edge Cases
If you might get inputs with extra spaces (e.g., 94107-1532), add a trim() first to clean up the input before processing:
return zipCode.trim().replaceAll("-\d{4}$", "");
内容的提问来源于stack exchange,提问作者user14190656

