企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
# Java 正则表达式 – 美国邮政编码验证 > 原文: [https://howtodoinjava.com/regex/us-postal-zip-code-validation/](https://howtodoinjava.com/regex/us-postal-zip-code-validation/) 在此 [Java 正则表达式教程](https://howtodoinjava.com/java-regular-expression-tutorials/)中,我们将学习使用正则表达式来**验证美国邮政编码**。 您也可以修改正则表达式以使其适合任何其他格式。 ## 1\. 有效的美国邮政编码模式 美国邮政编码(美国邮政编码)允许五位数和九位数(称为`ZIP + 4`)格式。 例如。 有效的邮政编码应匹配`12345`和`12345-6789`,但不能匹配`1234`、`123456`、`123456789`或`1234-56789`。 > 正则表达式:`^[0-9]{5}(?:-[0-9]{4})?$` ```java ^ # 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\. 美国邮政编码验证示例 ```java 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 ``` 那很容易,对吗? 向我提供有关**如何使用正则表达式**验证美国邮政编码的问题。 学习愉快!