-1

I’ve lots of 9-digit zip codes like shown below.

94107-1532
94107-1532
94107-1535
94107-1511

The first part is the first five digits of the zip code which indicates the destination post office or delivery area. The last 4 digits of the nine-digit ZIP Code represents a specific delivery route within that overall delivery area. I wanted to remove the last 4 digits starting including the Hyphen symbol(-). I tried the below expression, but no luck!

public static String removeRoute(String zipCode) {
    return zipCode.replaceAll("-\\d$", "");
}

4 Answers4

2

\\d only matches one digit character.

Use \\d+ to match multiple or \\d{4} to match exactly four

martinspielmann
  • 536
  • 6
  • 19
2

I wouldn't even use regex; just use String#split:

String input = "94107-1532";
String zip = input.split("-")[0];
String poBox = input.split("-")[1];
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
1

You are matching a hyphen and a single digit at the end of the string.

A bit more precise match would be to capture the first 5 digits in a group and match the hyphen and 4 digits at the end. In the replacement use group 1

^(\d{5})-\d{4}$

Regex demo

Or if the pattern can only occur at the end of the string, you can use for example a word boundary

\b(\d{5})-\d{4}$

Example code

public static String removeRoute(String zipCode) {
    return zipCode.replaceAll("^(\\d{5})-\\d{4}$", "$1");
}
The fourth bird
  • 154,723
  • 16
  • 55
  • 70
0

You can use an asterisk or plus sign right after the \d shorthand.

zipCode.replaceAll("-\\d+$", "");

OR

zipCode.replaceAll("-\\d*$", "");

The asterisk or star (*) tells the engine to attempt to match the preceding token zero or more times and the plus (+)tells the engine to attempt to match the preceding token once or more.

1218985
  • 7,531
  • 2
  • 25
  • 31