可以使用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));