使用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 年会公司新年祝福语简短