import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
final String regex = "(?sm)^0(?:(?!^0).)*?(?:kryptonite|stalagmite)";
final String string = "00:20314 lorem ipsum\n"
+ " want this\n"
+ " kryptonite\n\n"
+ "00:02314 quux\n"
+ " padding\n"
+ " dont want this\n\n"
+ "00:03124 foo\n"
+ " neither this\n\n"
+ "00:01324 foo\n"
+ " but we want this\n"
+ " stalagmite\n\n"
+ "00:02134 tralala\n"
+ " not this\n\n"
+ "00:03124 bar foo\n"
+ " and we want this\n"
+ " kryptonite but not this(!)\n\n"
+ "00:02134 foo bar\n"
+ " and not this either\n\n"
+ "00:01234 dolor sit amet\n"
+ " EOF";
final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
System.out.println("Full match: " + matcher.group(0));
for (int i = 1; i <= matcher.groupCount(); i++) {
System.out.println("Group " + i + ": " + matcher.group(i));
}
}
}
}
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Java, please visit: https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html