首页 > 解决方案 > 邮政编码的正则表达式模式

问题描述

我正在尝试为 4 位连字符或由 3 位数字连续的空格编写正则表达式模式,例如

1234 123
1234-123

我已经尝试过了,但它不符合要求

^\\d{4}[-]{0,1}\\d{3}$

标签: javaregex

解决方案


Just include a space in the character class. If the hyphen or space is optional, add a ? after it.

^\d{4}[ -]\d{3}$

Note that when using String#matches, you do not need to include the start (^) and end ($) anchors.

System.out.println("1234-123".matches("\\d{4}[ -]\\d{3}")); // true

推荐阅读