在Java中,正则表达式以零长度行开始,并继续跨行
我想匹配以下内容:一个零长度的行,在非零长度的行之间继续匹配,直到在一行中匹配一个特定的字符串。例如:比赛从一条零长度的线开始,一直持续到到达终点:在Java中,正则表达式以零长度行开始,并继续跨行,java,regex,newline,Java,Regex,Newline,我想匹配以下内容:一个零长度的行,在非零长度的行之间继续匹配,直到在一行中匹配一个特定的字符串。例如:比赛从一条零长度的线开始,一直持续到到达终点: 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
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
有什么建议吗
谢谢这应该可以做到:
(?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()+"<-");
}
}
}
确保设置了“匹配多行”标志,表达式为
“\\n(\\n.*STOP)”
。第一个(也是唯一一个)匹配组将生成您的结果。在DOS和windows系统上,使用“\\r\\n”
代替“\\n”嗨,巴特-太棒了-谢谢你的帮助。现在解剖它。Hi Bart,应该提到,应该从非零行之前的第一个空白行开始匹配。如果文档前面有其他空行,则匹配从第一行开始。我的解决方案应该这样做,您可能需要执行group()
而不是group(1)
,以将空行包括在匹配中。嗨,巴特-结合您对我的另一个问题的回答,我使用以下内容:(?s)\n\n(?(?!\n\n.)*别再说了,谢谢。
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
(?ms)^$(.+)STOP