2014-03-19 25 views
2

我有很多,其中存储样值的字符串:正则表达式,以适应无序列表

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

正如你可以在上面看到的 - 有三个组,每个组由固定长度的一个或多个值的,但给定组中的值可以按任何顺序发生(如果它是上升或下降,则不定义)。

我正在通过使用正则表达式查看数值组,并且我坚持用于检测给定组(即(40|21|33))中是否存在一组值(即20 or 31)的方法。

我做了正则表达式,用于检测是否有的即20 or 31值的任何,但是当有指定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) 
+0

要么你不是很清楚,要么我太愚蠢,无法理解你的问题 – aelor

+0

@aelor做了很少的编辑,也许这可以帮助 –

回答

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

+0

谢谢,这正是我一直在寻找的。 –