正则表达式适合无序列表

时间:2014-03-19 10:07:36

标签: java regex

我有很多字符串,其中存储的值如下:

(40|21|33)(111|222|333)(1|2)

如上所示 - 有三个组,每个组由一个或多个常量长度值组成,但给定组中的值可以按任何顺序出现(如果它是升序或降序则不定义)。 / p>

我正在使用正则表达式查看值组,我坚持使用方法,目的是检测给定组中是否存在一组值(即20 or 31)(即(40|21|33))。 / p>

我制作了正则表达式,用于检测是否存在20 or 31 ANY 值,但只有在指定了 ALL 值时才适合:

(\()([0-9]{2}(\|)?)*((20(\|)?)|(31(\|)?))([0-9]{2}(\|)?)*(\))

是否有办法检测给定组中是否 ALL 给定值,假设组中的值顺序未知?

只是为了澄清

(40|31|20) - should fit since there are all values of search group (20,31)
(40|22|20) - should not fit since there is only one value of search group (20,31)

1 个答案:

答案 0 :(得分:2)

您可以使用positive lookahead assertions执行此操作:

\(               # Match (
(?=[^()]*\b21\b) # Assert that 21 can be matched within this group
(?=[^()]*\b33\b) # Assert that 33 can be matched within this group
\d+              # Match a number    
(?:              # Start of non-capturing group:
 \|              #  Match |
 \d+             #  Match a number
)*               # any number of times, including 0
\)               # Match )

或者,在Java中:

Pattern regex = Pattern.compile(
    "\\(                # Match (\n" +
    "(?=[^()]*\\b21\\b) # Assert that 21 can be matched within this group\n" +
    "(?=[^()]*\\b33\\b) # Assert that 33 can be matched within this group\n" +
    "\\d+               # Match a number    \n" +
    "(?:                # Start of non-capturing group:\n" +
    " \\|               #  Match |\n" +
    " \\d+              #  Match a number\n" +
    ")*                 # any number of times, including 0\n" +
    "\\)                # Match )", 
    Pattern.COMMENTS);

live on regex101.com