Joe
Joe

Reputation: 15349

How do I prevent exclamations via a regex

public static final String REGEX_ADDRESS_ZIP = "^[0-9\\ -.]+$";

The above regex for validating zip code seems to allow exclamation (!) even though I haven't allowed it here. Not sure what the mistake is? Do I need to change the regex pattern

Upvotes: 7

Views: 294

Answers (1)

Amarghosh
Amarghosh

Reputation: 59461

The hyphen - is a metacharacter inside character classes unless it is the first or last character. Change it to:

^[0-9\\ .-]+$

[0-9\\ -.] means any character from 0 to 9 (all digits), the backslash \, and any character from space (ASCII 32) to period (ASCII 46) which translates to:

 !"#$%&'()*+,-.

Upvotes: 10

Related Questions