简体   繁体   English

字符序列之间的匹配-之前出现

[英]Matching between char sequences - first occurence before

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. 也就是说,以END结尾,回到END之前AA的第一个出现。 (Language is Java) (语言是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. 并且如果AAEND之间可能存在换行符,请在正则表达式的开头添加(?s) (DOT-ALL标志)。

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. 这将创建扩展到“ END”的子字符串,并在该子字符串中查找搜索字符串的最后一次出现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM