正则表达式 - 捕获重复数字(不是数字)

fel*_*cao 2 java regex numbers repeat

我正在尝试用Java编写一个检查String的方法,并允许它只包含数字和逗号.此外,没有重复的数字.

例如:

  • 11,22,33 - 还行吧
  • 22,22,33 - 这不行

我已经使用正则表达式和Set<String>(下面)的组合完成了它的初稿,但是正在寻找更好的东西,最好只使用正则表达式.

public boolean isStringOk(String codes) {
    if(codes.matches("^[0-9,]+$")){ 
        Set<String> nonRepeatingCodes = new LinkedHashSet<String>();
        for(String c: codigoRoletas.split(",")){
            if(nonRepeatingCodes.contains(c)){
                return false;
            }
            else{
                nonRepeatingCodes.add(c);
            }
        }
        return true;
     }
    return false;
}
Run Code Online (Sandbox Code Playgroud)

有没有人知道这是否可以使用正则表达式?

Mar*_*der 6

我怀疑这是明智的(正如Jarrod Roberson所提到的那样),因为对你的项目中的任何编码人员来说很难理解.但只有正则表达式才有可能:

^(?:(\d+)(?!.*,\1(?!\d)),)*\d+$
Run Code Online (Sandbox Code Playgroud)

理性的双阴性前瞻使其有点难以理解.但这是一个解释:

^                # anchor the regex to the beginning of the string
(?:              # subpattern that matches all numbers, but the last one and all commas
    (\d+)        # capturing group \1, a full number
    (?!          # negative lookahead, that asserts that this number does not occur again
        .*       # consume as much as you want, to look through the whole string
        ,        # match a comma
        \1       # match the number we have already found
        (?!\d)   # make sure that the number has ended (so we don't get false negatives)
    )            # end of lookahead
    ,            # match the comma
)*               # end of subpattern, repeat 0 or more times
\d+              # match the last number
$                # anchor the regex to the beginning of the string
Run Code Online (Sandbox Code Playgroud)

请注意,这只是一般的正则表达式,不是特定于Java.在Java中,您需要转义每个反斜杠,否则它将无法进入正则表达式引擎:

^(?:(\\d+)(?!.*,\\1(?!\\d)),)*\\d+$
Run Code Online (Sandbox Code Playgroud)