0

I got a String s = "HFGFHFFHSSH". What I want as output is every possible substring combination between 'H'

The output of the above String should be HFGFH HFFH HSSH

I tried the following:

String s = "HFGFHFFHSSH";  
Pattern pattern = Pattern.compile("H(.*?)H");
Matcher matcher = pattern.matcher(s);
while (matcher.find()){
  System.out.println(matcher.group(0));
}

Unfortunalety the output is missing one substring resulting in HFGFH HSSH

2

1 Answer 1

2

You should be using a lookahead regex for this and capture the value from inside the lookahead:

(?=(H[^H]*H))
  • (?=...) is positive lookahead that asserts presence of text surrounded by H on either side
  • (...) inside the lookahead is for capturing the matched value in group #1

RegEx Demo

Code:

String s = "HFGFHFFHSSH";  
final Pattern pattern = Pattern.compile("(?=(H[^H]*H))");
Matcher matcher = pattern.matcher(s);

while (matcher.find()) {
   System.out.println(matcher.group(1));
}
Sign up to request clarification or add additional context in comments.

1 Comment

The regex101 site enlightens me what really is going on in the regex stuff. :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.