0
之前,我有这样的字符串:匹配 - 第一次出现
"This is AA and this is AA and this is AA and this is the END blah blah"
我想匹配:
"AA and this is the END"
即END结束,回到前AA中第一次出现结束。 (语言是Java的)
之前,我有这样的字符串:匹配 - 第一次出现
"This is AA and this is AA and this is AA and this is the END blah blah"
我想匹配:
"AA and this is the END"
即END结束,回到前AA中第一次出现结束。 (语言是Java的)
试试这个:
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'
另一种答案:
str.substring(0, str.lastIndexOf("END")).lastIndexOf("AA");
这将创建延伸到“END”的字符串,发现子字符串中搜索字符串的最后一次出现。
你是上师。谢谢 – 2009-11-13 13:49:12
不客气理查德。是的,我知道一些正则表达式技巧,但是这里有很多人知道更多! – 2009-11-13 13:54:47