capturing group of consecutive digits using regex

Ahmad :

i'm trying to capture only the two 6's adjacent to each other and get how many times did it occur using regex like if we had 794234879669786694326666976 the answer should be 2 or if its 66666 it should be zero and so on i'm using the following code and captured it by this (66)* and using matcher.groupcount() to get how many times did it occur but its not working !!!

package me;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class blah {

    public static void main(String[] args) {

       // Define regex to find the word 'quick' or 'lazy' or 'dog'
    String regex = "(66)*";
    String text = "6678793346666786784966";

    // Obtain the required matcher
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(text);
    int match=0;

    int groupCount = matcher.groupCount();
    System.out.println("Number of group = " + groupCount);

    // Find every match and print it
    while (matcher.find()) {

        match++;
    }
    System.out.println("count is "+match);
}

}
Tim Biegeleisen :

One approach here would be to use lookarounds to ensure that you match only islands of exactly two sixes:

String regex = "(?<!6)66(?!6)";
String text = "6678793346666786784966";

Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(text);

This finds a count of two, for the input string you provided (the two matches being the 66 at the very start and end of the string).

The regex pattern uses two lookarounds to assert that what comes before the first 6 and after the second 6 are not other sixes:

(?<!6)   assert that what precedes is NOT 6
66       match and consume two 6's
(?!6)    assert that what follows is NOT 6

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=77607&siteId=1