Попробуйте это:
AA(?:(?!AA).)*END
Демо:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String text = "This is AA and this is AA and this is AA and this is the END blah blah";
Matcher m = Pattern.compile("AA(?:(?!AA).)*END").matcher(text);
while(m.find()) {
System.out.println("match ->"+m.group()+"<-");
}
}
}
И если между AA
и END
могут быть разрывы строк, добавьте (?s)
(флаг DOT-ALL) в начале вашего регулярного выражения.
Краткое объяснение:
AA # match 'AA'
(?: # open non-capturing group 1
(?!AA). # if 'AA' cannot be seen, match any char (except line breaks)
)* # close non-capturing group 1 and repeat it zero or more times
END # match 'END'