The regular expression (?=(ab.*cd)) will group such matches in group 1, as you can see:
import java.util.regex.*; public class Main { public static void main(String[] args) throws Exception { Matcher m = Pattern.compile("(?=(ab.*cd))").matcher("ab1ab2ab3ab4cd"); while (m.find()) { System.out.println(m.group(1)); } } }
which produces:
ab1ab2ab3ab4cd ab2ab3ab4cd ab3ab4cd ab4cd
You need to look ahead, (?= ... ) , otherwise you will get only one match. Please note that the regular expression will not give the desired results if your line contains more than 2 cd . In this case, you will have to resort to some manual string algorithm.
source share