Java 正则表达式 – 美国邮政编码验证

Java 正则表达式 – 美国邮政编码验证

原文: https://howtodoinjava.com/regex/us-postal-zip-code-validation/

在此 Java 正则表达式教程中,我们将学习使用正则表达式来验证美国邮政编码。 您也可以修改正则表达式以使其适合任何其他格式。

1. 有效的美国邮政编码模式

美国邮政编码(美国邮政编码)允许五位数和九位数(称为ZIP + 4)格式。

例如。 有效的邮政编码应匹配1234512345-6789,但不能匹配12341234561234567891234-56789

正则表达式:^[0-9]{5}(?:-[0-9]{4})?$

^           # Assert position at the beginning of the string.
[0-9]{5}    # Match a digit, exactly five times.
(?:         # Group but don't capture:
  -         #   Match a literal "-".
  [0-9]{4}  #   Match a digit, exactly four times.
)           # End the non-capturing group.
  ?         #   Make the group optional.
$           # Assert position at the end of the string.

2. 美国邮政编码验证示例

List<String> zips = new ArrayList<String>();

//Valid ZIP codes
zips.add("12345");  
zips.add("12345-6789");  

//Invalid ZIP codes
zips.add("123456");  
zips.add("1234");  
zips.add("12345-678");

zips.add("12345-67890");

String regex = "^[0-9]{5}(?:-[0-9]{4})?$";

Pattern pattern = Pattern.compile(regex);

for (String zip : zips)
{
	Matcher matcher = pattern.matcher(zip);
	System.out.println(matcher.matches());
}

Output:

true
true

false
false
false
false

那很容易,对吗? 向我提供有关如何使用正则表达式验证美国邮政编码的问题。

学习愉快!