正则表达式匹配java中的特定单词

时间:2012-08-18 18:11:42

标签: java regex

E.g。这3个单词[AB,CD,EF]的任何组合都应该通过正则表达式。此外,它不应该允许重复。

感谢。

3 个答案:

答案 0 :(得分:1)

我不建议使用正则表达式。但有可能:

boolean foundMatch = subjectString.matches(
    "(?x)                  # Verbose regex:\n" +
    "(?!.*(AB|CD|EF).*\\1) # Make sure there are no dupes in the string\n" +
    "\\s*                  # Match optional whitespace.\n" +
    "(?:AB|CD|EF)          # Match one of the three candidates\n" +
    "(?:                   # Try to match...\n" +
    " \\s*,\\s*            #  a comma, optionally surrounded by whitespace\n" +
    " (?:AB|CD|EF)         #  followed by one of the candidates\n" +
    ")*                    # zero or more times\n" +
    "\\s*                  # Match optional whitespace.");

答案 1 :(得分:0)

嗯,显而易见的解决方案只是列举正则表达式中的所有15种可能性 - 只需要一点点工作,你可以分解一些术语并获得一个稍微更紧凑的正则表达式 - 但是不会有另一种方法用正则表达式表达那些约束。

答案 2 :(得分:0)

“没有重复”是指计数。一般的正则表达式不能这样做,因此它是错误的工具。

相关问题