Java 匹配模式前两行的正则表达式

Java regex to match previous 2 lines of a pattern

something Line One
something Line two 
Last annotated on December 31, 2014

I don't care what is in between. Anything can go here. Any number of lines
I don't care what is in between. Anything can go here. Any number of lines

Something Line three
something line four
Last annotated on November 15, 2014

我想写一个正则表达式来匹配

something Line One
something Line two 
Last annotated on December 31, 2014

Something Line three
something line four
Last annotated on November 15, 2014

我在下面写了适用于 Sublimetex 的正则表达式,但同样的正则表达式不适用于 java。

.*\n.*\nLast annotated on \w* \d{2}, \d{4}

下面是与模式不匹配的 java 代码。

String regex = ".*\n.*\nLast annotated on \w* \d{2}, \d{4}";
Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);

您需要使用具有 find 功能的 Pattern 和 Matcher 类。

String s = "something Line One\n" + 
        "something Line two \n" + 
        "Last annotated on December 31, 2014\n" + 
        "\n" + 
        "I don't care what is in between. Anything can go here. Any number of lines\n" + 
        "I don't care what is in between. Anything can go here. Any number of lines\n" + 
        "\n" + 
        "Something Line three\n" + 
        "something line four\n" + 
        "Last annotated on November 15, 2014";
Matcher m = Pattern.compile(".*[\r\n]+.*[\r\n]+Last annotated on \w* \d{2}, \d{4}").matcher(s);
while(m.find())
{
    System.out.println(m.group());
}

输出:

something Line One
something Line two 
Last annotated on December 31, 2014
Something Line three
something line four
Last annotated on November 15, 2014