java - Java 中的正则表达式以零长度行开始并跨行继续

标签 java regex newline

我想要匹配以下内容:零长度的行,匹配继续跨越非零长度的行,直到在行中匹配特定字符串。例如:比赛从零长度线开始,一直持续到到达 STOP:

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

将输出:

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

关于java - Java 中的正则表达式以零长度行开始并跨行继续,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1728754/

相关文章:

javascript - 正则表达式字符恰好出现两次

python - 为什么我的 re.search 命令不起作用?

php将多维数组内爆到制表符分隔行

node.js - 在 Node.js 中压缩包含换行符的文本文件会导致 gzip 文件损坏

php - require_once() 在文件开头添加换行符

java - 从 PlayFramework 切换到 SpringMVC

java - 我的应用程序在启动时崩溃,我不确定为什么

java - 模拟库调用

java - 左加入 hql 中的第一场比赛

regex - 从 scala 进程运行 perl 命令