可以使用java.util.regex.Pattern.matches()方法验证邮政编码。此方法匹配邮政编码和给定输入邮政编码的正则表达式,如果匹配则返回true,否则返回false。
演示此过程的程序如下:
示例publicclassDemo{
publicstaticvoidmain(Stringargs[]){
StringzipCode="83592-1537";
Stringregex="\\d{5}(-\\d{4})?";
System.out.println("Thezipcodeis:"+zipCode);
System.out.println("Istheabovezipcodevalid?"+zipCode.matches(regex));
}
}
输出结果Thezipcodeis:83592-1537
Istheabovezipcodevalid?true
现在让我们了解上面的程序。
邮政编码被打印出来。Pattern.matches()方法匹配邮政编码和给定输入邮政编码的正则表达式,并打印结果。演示此代码段如下:StringzipCode="83592-1537";
Stringregex="\\d{5}(-\\d{4})?";
System.out.println("Thezipcodeis:"+zipCode);
System.out.println("Istheabovezipcodevalid?"+zipCode.matches(regex));