3

The case is that, I want to find string which satisfies "c+d" in a string "cccd". My code is as follows,

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 what I want is to get all the possible results, including nested ones, which are cd, ccd and cccd. How should I fix it, thanks in advance.

VLAZ
  • 26,331
  • 9
  • 49
  • 67
Maytree23
  • 125
  • 1
  • 10

1 Answers1

5

Just Use a lookahead to capture the overlapping characters,

(?=(c+d))

And finally print the group index 1.

DEMO

Your code would 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
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274