0

我希望我在搜索字符串mPattern中匹配FFF1FFF3字符串至少 4 次。我写了两个模式版本,但没有一个给出任何匹配。

Pattern mPattern = Pattern.compile("(FFF1|FFF3){4,}");

版本2:

Pattern mPattern = Pattern.compile("(FFF1{4,}|FFF3{4,})");

搜索字符串是(示例):

0DCB1C992B37173740244875C143D50ACDBA0422CD01D73D3C78F05ED7BBC2B33F9D78A7FFF342C0241C6B56B11EC1867984C20F42A4FAC5B9C0
42220314C006D94E124673CD4CC27FC2FCE12215410F12086BE5A3EDFC6DB2BEB0EAEC6EAAA4BF997FFB3337F914AB1A89C808EA6D338912D72E
99CE11E899999D3AE1092590FB2B71D736DC544B0AFD1035A3FFF340C00E178B62E5BE48C46F04B8EFC106AE3F17DDE08B5FD48672EBEABB216A
8438B6FB3B33BF91D3F3EBFCE14184320532ABA37FFD59BFF6ABAD1AA9AADEE73220679D2C7DDBAB766433A99D8CA752B383067465691750A24A
00F32A5078E29258F6D87A620AFFF342C00A158B22E5BE5944BAE8BA2C54739BE486B719A76DF5FD984D5257DBEAC43B238598EFAB3592DE8DD5
4

1 回答 1

5

The pattern "(FFF1|FFF3){4,}" will match FFF1 or FFF3 placed adjacent, with a repetition of 4 or more. I guess there can be any characters between multiple occurrences. In that case, use the following regex:

"^(?:.*?(FFF1|FFF3)){4,}.*$"

.*? match any character till the next FFF1 or FFF3, then match FFF1|FFF3. Repeat this sequence 4 or more times (applied on entire non-capturing group).

You can use the above pattern directly with String#matches(String) method. Or, if you are building Pattern and Matcher objects, then just use the following pattern with Matcher#find() method:

"(?:.*?(FFF1|FFF3)){4,}"

Working code:

String str = "...";  // initialize

Pattern mPattern = Pattern.compile("(?x)" +  // Ignore whitespace
                        "(?:            " +  // Non-capturing group
                        "   .*?         " +    // 0 or more repetition of any character
                        "   (FFF1|FFF3) " +    // FFF1 or FFF3
                        "){4,}          "    // Group close. Match group 4 or more times
                                  );  

Matcher matcher = mPattern.matcher(str);        
System.out.println(matcher.find()); 
于 2013-10-23T10:31:32.923 回答