我会在第一个字母之后的每个后续部分使用“一次或根本不”量词的组合,并向后看以验证输入的前面部分。
例如:
// |first letters (1 to 3)
// | if 3 letters precede...
// | digits (1 to 7)
// | if 7 digits precede...
// | 3 letters
Pattern p = Pattern.compile("[a-zA-Z]{1,3}((?<=[a-zA-Z]{3})\\d{1,7})?((?<=\\d{7})[a-zA-Z]{3})?");
String[] inputs = {"XYZ0001112CCC", "A", "AB", "ABC", "ABC12", "ABC123", "A1", "AB2", "ABCD123","ABC1234567XY1"};
Matcher m;
for (String input: inputs) {
m = p.matcher(input);
System.out.println("Input: " + input + " --> Matches? " + m.matches());
}
输出:
Input: XYZ0001112CCC --> Matches? true
Input: A --> Matches? true
Input: AB --> Matches? true
Input: ABC --> Matches? true
Input: ABC12 --> Matches? true
Input: ABC123 --> Matches? true
Input: A1 --> Matches? false
Input: AB2 --> Matches? false
Input: ABCD123 --> Matches? false
Input: ABC1234567XY1 --> Matches? false
注意
我已将您的\\w 表达式更改为字符类[a-zA-Z],因为\\w 也可以验证数字。
[a-zA-Z] 的替代品是:
\\p{Alpha}
-
[a-z] 带有 Pattern.CASE_INSENSITIVE 标志
最后说明
我的Pattern 将最后一个字母作为一个 3 字母组。
如果您还接受 1 或 2 个字母,则只需将最后一个量词表达式 {3} 更改为 {1,3}。