Java – Captures a set of consecutive numbers using regular expressions

Captures a set of consecutive numbers using regular expressions… here is a solution to the problem.

Captures a set of consecutive numbers using regular expressions

I’m trying to catch just two 6s next to each other and use a regular expression to get how many times it happens, like if we have 794234879669786694326666976 the answer should be 2 or it should be 66666 to zero, and so on but it doesn’t work !!!

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);
}

}

Solution

One way to do this is to use a look around to make sure you match exactly two sixes on islands:

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

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

For the input string you provide, this finds two counts (the two matches are 66 at the beginning and end of the string).

The regular expression pattern uses two round looks to assert that what precedes the first 6 and after the second 6 is not the other six:

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

Related Problems and Solutions