Java环境下校验无重复预定义逗号分隔字符串的正则表达式需求
解决方案:Java中校验无重复预定义字符串的正则表达式
Hey, let's fix this duplicate detection gap in your regex. Your current pattern handles the basic comma-separated format, but it doesn't track which values have already appeared. Here's how to adapt it for Java while adding duplicate checking:
核心思路
We'll use a negative lookahead assertion at the start of the regex to scan the entire input and ensure no predefined string appears more than once. Then we'll keep your original format-matching logic to validate the comma-separated structure.
最终正则表达式
^(?!.*\\b(IN|THE|BUSH|COM|NET|ALL)\\b.*\\b\\1\\b)(?:\\s*(IN|THE|BUSH|COM|NET|ALL)\\s*,?\\s*)+$
Let's break down what this does:
^(?!.*\\b(IN|THE|BUSH|COM|NET|ALL)\\b.*\\b\\1\\b): This is the critical duplicate-checking part. It's a negative lookahead that asserts: "There is no occurrence of any predefined string that appears twice in the input". The\\bensures we match full strings (so we don't accidentally flag "NET" because it contains "IN").(?:\\s*(IN|THE|BUSH|COM|NET|ALL)\\s*,?\\s*)+$: This is your original format logic, cleaned up a bit. It matches one or more predefined strings, allowing optional whitespace around each string and optional trailing commas.
Java代码示例
Here's a ready-to-use validator class to test this:
import java.util.regex.Pattern; import java.util.regex.Matcher; public class UniqueStringValidator { // Precompile the pattern for performance private static final Pattern VALIDATION_PATTERN = Pattern.compile( "^(?!.*\\b(IN|THE|BUSH|COM|NET|ALL)\\b.*\\b\\1\\b)(?:\\s*(IN|THE|BUSH|COM|NET|ALL)\\s*,?\\s*)+$" ); public static boolean isValidInput(String input) { if (input == null || input.trim().isEmpty()) { return false; // Adjust this if empty input should be allowed } Matcher matcher = VALIDATION_PATTERN.matcher(input); return matcher.matches(); } public static void main(String[] args) { // Test cases System.out.println(isValidInput("IN, THE, COM")); // true (valid, no duplicates) System.out.println(isValidInput("IN, COM, THE, COM")); // false (duplicate "COM") System.out.println(isValidInput("IN, THE , BUSH")); // true (whitespace handled) System.out.println(isValidInput("NET, NET")); // false (duplicate "NET") System.out.println(isValidInput("ALL")); // true (single valid value) } }
注意事项
- Word Boundaries: The
\\bis important here—if your predefined strings ever have overlapping substrings (e.g., "IN" and "INT"), it prevents false positives. Since your current set doesn't have this, it's still a safe practice. - Escaping: Remember that in Java strings, backslashes need to be doubled (
\\) to be recognized in regex. - Trailing Commas: The regex allows trailing commas (like "IN, THE,"). If you want to disallow this, modify the format part to:
This ensures each string is either followed by a comma (and another string) or the end of the input.(?:\\s*(IN|THE|BUSH|COM|NET|ALL)\\s*(?:,\\s*|$))+
内容的提问来源于stack exchange,提问作者Ezell Buoee
相关产品推荐
相关产品推荐

