Regex, начинающийся со строки нулевой длины и продолжающийся через строки в Java - PullRequest
1 голос
/ 13 ноября 2009

Я хочу сопоставить следующее: строка нулевой длины, причем сопоставление продолжается по строкам ненулевой длины до тех пор, пока конкретная строка не будет сопоставлена ​​в строке. Например: матч начинается с линии нулевой длины и продолжается до достижения СТОП:

Some random text I don't care about

The match starts at the beginning of this line
The match continues across this line
The match stops here STOP more
text I don't care about

Есть предложения?

Спасибо

Ответы [ 3 ]

3 голосов
/ 13 ноября 2009

Это должно сделать это:

(?ms)^[ \t]*+$\s*+((?:(?!STOP).)*+)

Немного демо:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main { 
    public static void main(String[] args) {
        String text = "Some random text I don't care about"      + "\n" +
                ""                                               + "\n" +
                "The match starts at the beginning of this line" + "\n" +
                "The match continues across this line"           + "\n" +
                "The match stops here STOP more"                 + "\n" +
                "don't care about"                               + "\n" +
                ""                                               + "\n" +
                ""                                               + "\n" +
                ""                                               + "\n" +
                "foo"                                            + "\n" +
                "barSTOP"                                        + "\n" +
                "text I don't care about";
        Matcher m = Pattern.compile("(?ms)^[ \t]*+$\\s*+(?:(?!STOP).)*+").matcher(text);
        while(m.find()) {
            System.out.println("match ->"+m.group()+"<-");
        }
    }
}

, который выдаст:

match ->
The match starts at the beginning of this line
The match continues across this line
The match stops here <-
match ->


foo
bar<-

Небольшое объяснение:

(?ms)               # enable mutli-line and dot-all
^[ \t]*+$           # match and empty line
\s*+                # match the line break
(                   # start group 1
  (?:(?!STOP).)     #   if the string 'STOP' cannot be seen, match any character
  *+                #   match the previous zero or more times (possessively)
)                   # stop group 1
0 голосов
/ 13 ноября 2009
(?ms)^$(.+)STOP
0 голосов
/ 13 ноября 2009

Убедившись, что вы установили флаг «соответствовать многострочным», выражение будет "\\n(\\n.*STOP)". Первая (и единственная) группа совпадений дает ваш результат. В системах DOS и Windows используйте "\\r\\n" вместо "\\n".

...