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.

2

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.