char序列之间的匹配 - 先发生之前

时间:2009-11-13 13:25:37

标签: java regex

我有一个字符串:

"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结束,回到END之前的第一次AA出现。 (语言是Java)

2 个答案:

答案 0 :(得分:4)

试试这个:

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()+"<-");
        }
    }
}

如果AAEND之间可以有换行符,请在正则表达式的开头添加(?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'

答案 1 :(得分:1)

另一个答案:

str.substring(0, str.lastIndexOf("END")).lastIndexOf("AA");

这会创建扩展为“END”的子字符串,并在该子字符串中查找搜索字符串的最后一次出现。