I have a string like:
"This is AA and this is AA and this is AA and this is the END blah blah"
I want to match:
"AA and this is the END"
ie, ending in END, back to the first occurance of AA before END. (Language is Java)
I have a string like:
"This is AA and this is AA and this is AA and this is the END blah blah"
I want to match:
"AA and this is the END"
ie, ending in END, back to the first occurance of AA before END. (Language is Java)
Try this:
AA(?:(?!AA).)*END
A demo:
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()+"<-");
}
}
}
And if there can be line breaks between the AA
and END
, add a (?s)
(DOT-ALL flag) at the start of your regex.
A short explanation:
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'
An alternative answer:
str.substring(0, str.lastIndexOf("END")).lastIndexOf("AA");
This creates the substring extending to "END" and finds the last occurrence of your search string within that substring.