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

motaa
  • 327
  • 2
  • 11

1 Answers1

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));
}
anubhava
  • 761,203
  • 64
  • 569
  • 643