使用 Java 正则表达式验证邮政编码


可以使用 java.util.regex.Pattern.matches() 方法验证邮政编码。此方法匹配邮政编码的正则表达式和给定的输入邮政编码,并在两者匹配时返回 true,否则返回 false。

演示这一点的程序如下

示例

 实时演示

public class Demo {
   public static void main(String args[]) {
      String zipCode = "83592-1537";
      String regex = "\d{5}(-\d{4})?";
      System.out.println("The zip code is: " + zipCode);
      System.out.println("Is the above zip code valid? " + zipCode.matches(regex));
   }
}

输出

The zip code is: 83592-1537
Is the above zip code valid? true

现在让我们了解上述程序。

邮政编码已打印。Pattern.matches() 方法匹配邮政编码的正则表达式和给定的输入邮政编码,并将结果打印出来。演示这一点的代码片段如下

String zipCode = "83592-1537";
String regex = "\d{5}(-\d{4})?";

System.out.println("The zip code is: " + zipCode);
System.out.println("Is the above zip code valid? " + zipCode.matches(regex));

更新时间:30-Jul-2019

1 千多次浏览

开启你的职业生涯

完成课程,获得认证

开始学习
广告
© . All rights reserved.