Reputation: 61
I need to verify that String zip is 5 numbers long and starts with 80, 81, 82, or 83. do I need a regex to do this?
I have tried boolean validZip = (zip.length() == 5 && zip.charAt(0) == 8 && zip.charAt(1) >= 0 && zip.charAt(1) <= 3);
but 80221 returns false for me.
Upvotes: 1
Views: 52
Reputation: 31841
Sure, you can use this regex
^8[0123]\d{3}$
And use it in java like this
String zipcode = "80882";
Pattern p = Pattern.compile("^8[0123]\\d{3}$");
Matcher m = p.matcher(zipcode);
boolean validZip = m.find();
Upvotes: 2
Reputation: 5557
Try this:
boolean validZip = (zip.length() == 5 && zip.charAt(0) == '8' && zip.charAt(1) >= '0' && zip.charAt(1) <= '3');
You were comparing ASCII values. To compare characters, you need to write them in single quote. If you want to compare ASCII values, then it can be done as following:
boolean validZip = (zip.length() == 5 && zip.charAt(0) == 56 && zip.charAt(1) >= 48 && zip.charAt(1) <= 51);
ASCII values for 0-9 ranges from 48-57.
Upvotes: 4