简体   繁体   中英

Regular expression to check if string has certain number of digits

I have address information and some junk in my DB and I have to just check if the string has zip code I need to process that. Can you explain how to check if a string has a 5 digits present. For example,

String addr = 10100 Trinity Parkway, 5th Floor Stockton, CA 95219; 

So it has to match this string as it is having 5 digit zip code. Any way to check using Java Regular Expression?

Update:

String addr = "10100 Trinity Parkway, 5th Floor Stockton, CA 95219"; 
String addressMatcher = "\\d{5}";
if(addr.matches(addressMatcher)){
System.out.println(addr);
}

Above is the code I am using after getting the answers but none of the regex matches and prints the addr. Am I doing anything wrong? Regards, Karthik

The simple expression is ".*\\\\d{5}$" , which says that you want any character 0 or more times, then any digit 5 times, and then the end of the string. Note that this accounts for needing to escape the slash in the Java string.

If you may have more characters at the end of the string, then you can append .* to the expression to match those. However, that may end up matching number in addresses as well, so make sure your data is in a consistent, expected format.

Regular expressions may not be sufficient in this case, since not all 5-digit numbers are actually zip codes. As well, some zip codes may include additional numbers (usually following a - after the first five digits.)

I am not quite sure if this is what you are looking for:

(\\w\\s*)+,(\\s*(\\w\\s*) ,) \\s*[AZ]{2}\\s*[1-9]{5}

This expression will match:
1 - any words with any spaces followed by comma,
2 - then optional repetitions of words separated by spaces followed by comma
3 - at the end , it is ended with two characters words (the state code), followed by zip code which is 5 digits (non-zero digits)
I hope this help

[Edit]
This expression will filter out numbers in the address that are not in the correct place to be zip code, like for example ( 10100) in your example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM