开发者

regex expression - specifying number of repeated character value in a string

how can i check for a pattern occuring a certain number of times?

eg:

4444444 => return 4

4444332 => return 4

4444431 => return 4

4443333 => return 0

4243424 => return ?

but if character 4 occurs less than 4 times then retu开发者_如何学编程rn 0

i am just looking for 4 here. if it appears more than or equal to 4 times then value returned would be 4. the other 3 numbers in the string can range from 1 to 3 only.

thank you.


If you need four consecutive 4s, it's just 4{4} or 4444. If they don't need to be consecutive, 4.*4.*4.*4 will do it. If it can be any number, but has to be four times, then ([1-4])\1{3} or ([1-4]).*\1.*\1.*\1 depending on whether you need them to be consecutive or not.


To check for 4 consecutive same digits between 1 to 4 you can use the regex:

([1-4])\1{3}


It looks like ^[1-3]*4[1-3]*4[1-3]*4[1-3]*4[1-4]*$ is what you basically need.

Match the '4' 4 times surrounded by numbers from 1-3. The last case basically says, after 4 is matched 4 times, there can be any numbers 1-4 till the end of the string. This works for the patterns you suggested above. The problem with the above expression is that if there is a failure, and your string is long (>100 chars), then you could have what is known as Catastrophic Backtracking (see comments below...). To avoid that, you will need possessive matchers, or the more commonly supported independent sub-expressions. That will look like (note, you could also do this with possessive matchers *+ etc):

^(?>[1-3]*)4(?>[1-3]*)4(?>[1-3]*)4(?>[1-3]*)4(?>[1-4]*)$


Then, to count the patterns:

public static void main(String[] args)
{
    String input = "44444123444441234444";
    Pattern pattern = Pattern.compile("4444");
    Matcher matcher = pattern.matcher(input);
    int count = 0;
    int lookupPosition = 0;

    while (matcher.find(lookupPosition))
    {
        count++;
        lookupPosition = matcher.start() + 1;
    }

    System.out.println(count);
}


You can use the pattern "(4[^4]*){4}"

  List<String> inputs = Arrays.asList("4444444", "4444332", "4443333", 
      "4243424", "4444431");
  Pattern pattern = Pattern.compile("(4[^4]*){4}");
  for(String input: inputs) {
    Matcher matcher = pattern.matcher(input);
    System.out.printf("Min 4 fours in '%s'? %b\n", input, matcher.find());
  }

Output:

Min 4 fours in '4444444'? true
Min 4 fours in '4444332'? true
Min 4 fours in '4443333'? false
Min 4 fours in '4243424'? true
Min 4 fours in '4444431'? true
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜