Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression: Zip Code only 9 or 10 Digits with Dash

Tags:

java

regex

We are allowing US Zip Codes as only (1) 9 digits, or (2) 10 digits with a dash before the last 4 digits.

The following regexp gives a compilation error:

private static final String USZIPCODE_MATCH_FORMAT_REGEXP = "^\d{5}[\\-]?\d{4}$";

Invalid escape sequence
like image 488
gene b. Avatar asked Apr 14 '26 16:04

gene b.


1 Answers

In Java you need to escape the \ as well. So, you need

"^\\d{5}[\\-]?\\d{4}$"

Also, you can specify the hyphen simply as

"^\\d{5}-?\\d{4}$"

The - is not special when used outside [].

like image 113
Ravi K Thapliyal Avatar answered Apr 17 '26 11:04

Ravi K Thapliyal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!