正则表达式技术求助:17位大写字母校验规则实现问题
Hey there! Let's sort out that regex problem you're facing. Your current pattern "\S^[I,O,Q][A-Z]" has a few key issues that are making it fail:
- The
^anchor is placed in the middle of the pattern, which is incorrect — it should only be used to mark the start of the string. - The
[I,O,Q]syntax includes commas as literal characters to match, and it's set to include those characters instead of excluding them. - The overall logic is disjointed:
\Smatches non-whitespace, but it's not combined correctly with the rest of the rules.
The Correct Regex
Here's a pattern that meets all your requirements, and I'll break down how it works:
String regEx = "^[A-Z&&[^IOQ]]{17}$";
Let's unpack each part:
^: Anchors the match to the start of the input string (ensures we're checking the entire input from the beginning).[A-Z&&[^IOQ]]: This is an intersection set — it matches any uppercase letter (A-Z), but excludes I, O, and Q. The&&operator lets us combine two sets: all uppercase letters, minus the three you want to block.{17}: Explicitly matches exactly 17 of the preceding valid characters (so you can even remove your separatestr.length() == 17check if you want, since the regex handles length too).$: Anchors the match to the end of the string (ensures there are no extra characters after the 17 valid ones).
Alternative (If You Prefer No Intersection Syntax)
If you're working in a context where intersection regex isn't supported (though Java fully supports it), you can explicitly list all allowed uppercase letters (omitting I, O, Q):
String regEx = "^[ABCDEFGHJKLMNPRSTUVWXYZ]{17}$";
How to Use It in Your Code
Here's how to integrate this into your existing check (either with or without the separate length check):
String input = yourInputString; String regEx = "^[A-Z&&[^IOQ]]{17}$"; if (input.matches(regEx)) { // Validation passed! } else { // Validation failed — handle accordingly }
This pattern will ensure your input is exactly 17 characters long, uses only uppercase letters, excludes I/O/Q, and has no spaces or special characters.
内容的提问来源于stack exchange,提问作者Schnitzel

