简体   繁体   English

用于检查字符串是否具有特定位数的正则表达式

[英]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. 您能解释一下如何检查字符串中是否有5位数字。 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. 因此,它必须匹配此字符串,因为它具有5位邮政编码。 Any way to check using Java Regular Expression? 有什么方法可以检查使用Java正则表达式吗?

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 此致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. 简单的表达式是".*\\\\d{5}$" ,它表示您希望任意字符0次或多次,然后任意数字5次,然后字符串的末尾。 Note that this accounts for needing to escape the slash in the Java string. 注意,这说明需要转义Java字符串中的斜杠。

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. 在这种情况下,由于并非所有5位数字实际上都是邮政编码,因此正则表达式可能不足。 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} (\\ 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, 1-带有空格的任何单词,后跟逗号,
2 - then optional repetitions of words separated by spaces followed by comma 2-然后是单词的可选重复,用空格分隔,后跟逗号
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) 3-在结尾处,以两个字符的单词(状态码)结尾,然后是5位(非零数字)的邮政编码。
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 此表达式将过滤出地址中邮政编码不正确的数字,例如您的示例中的(10100)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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