Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I prevent exclamations via a regex

Tags:

java

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

like image 577
Joe Avatar asked Jul 01 '10 10:07

Joe


1 Answers

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:

 !"#$%&'()*+,-.
like image 63
Amarghosh Avatar answered Nov 09 '22 12:11

Amarghosh