In java, when you use regex to search for patterns, how do you get the nested result?

The thing is, I want to find a string that matches "c + d" in "cccd". My code looks like this:

String str="cccd";
String regex="c+d";
Pattern pattern = Pattern.compile(regex);
Matcher matcher =pattern.matcher(str);
While(matcher.find()){
    System.out.println(matcher.group())
}

      

The result is only "cccd". But I want to get all possible results, including the nested ones, which are cd, ccd and cccd. How can I fix this, thanks in advance.

+3


source to share


1 answer


Just use lookahead to capture overlapping characters,

(?=(c+d))

      

Finally, print the group index 1.

DEMO



Your code will be,

String str="cccd";
String regex="(?=(c+d))";
Pattern pattern = Pattern.compile(regex);
Matcher matcher =pattern.matcher(str);
while(matcher.find()){
    System.out.println(matcher.group(1));
}

      

Output:

cccd
ccd
cd

      

+5


source







All Articles