使用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));热门推荐
10 祝女儿简短祝福语大全
11 大学新年祝福语简短创意
12 元旦适合的祝福语简短
13 朋友出远门祝福语简短
14 初六简短的祝福语
15 祝男孩生日祝福语简短
16 同事调离的祝福语简短
17 拜年红包的祝福语简短
18 妈妈生日祝福语简短励志