JAVA 中"ABC-1234"的正则表达式验证



如果我希望用户匹配,正则表达式是什么。"abc-1234"

所以3个字母(大写或小写)后面跟着4个数字。。。

以下是我到目前为止所拥有的(非常感谢!):

    if (id.matches("^[A-Z][a-zA-Z]{3}-[\d]{4}$")) {
        this.id = id;
    } else { 
        throw new IllegalArgumentException("Inventory ID must be in the "
            + "form of ABC-1234");
    }
}

Pattern Javadoc说(编辑/部分)

预定义的字符类

d    A digit: [0-9]

POSIX字符类(仅限US-ASCII)

p{Lower}     A lower-case alphabetic character: [a-z]
p{Upper}     An upper-case alphabetic character:[A-Z]
p{Alpha}     An alphabetic character:[p{Lower}p{Upper}]

所以你可以使用类似的东西

if (id.matches("\p{Alpha}{3}-\d{4}")) {

这应该能在中工作

if (id.matches("[a-zA-Z]{3}-[0-9]{4}")) {
    this.id = id;
} else { 
    throw new IllegalArgumentException("Inventory ID must be in the "
        + "form of ABC-1234");
}

下面的reg exp匹配3个字符,然后是四位

[a-zA-Z]{3}-[0-9]{4}

您的模式可以分解为以下部分:

  • [A-Z]
  • [a-zA-Z]{3}
  • -
  • [\d]{4}

在口语中,这是:1个大写字母加3个字母(总共4个)加短划线加4个数字。

只要把3换成2,它就会起作用。

生成的代码将要求第一个字母是大写的。如果你不想这样,就用其他答案中的一个。

最新更新