java - 正则表达式拆分 - 但包括换行符 - 包括 CR LF

标签 java arrays regex string

我有一个看似简单的情况,我需要在换行符上分割字符串序列(在Java中) - 但我需要输出中包含新行字符(应用程序的另一部分需要这些 - 以及原始值,不仅仅是任何换行符)。

下面的代码可以工作,但不包括 CRLF (\r\n)。仅包含其中一个角色。如果我重写正则表达式模式以仅包含\r\n 字符 ((?<=\r\n)),则相同的代码可以工作,但我无法弄清楚如何捕获所有这三个字符。 ((?<=\r\n)|(?<=\n)|(?<=\r)) 也不起作用,它仍然只匹配\r 或\n - 而不是两者。

        String text = "Heres is one line\r\n" +
                "and another\r" +
                "and another one\n" +
                "all with different line ending chars";

        List<String> textLinesWithDelimiters = Arrays.asList(text.split(("((?<=\\n)|(?<=\\r))")));

        for(String ln : textLinesWithDelimiters)
        {
            // ln should include the \n, \r, or \r\n characters
            System.out.println(ln);
        }

最佳答案

您可以使用匹配方法来代替:

String phrase = "Heres is one line\r\n" +
                "and another\r" +
                "and another one\n" +
                "all with different line ending chars";

Pattern p = Pattern.compile("\\V+|\\v+");
Matcher m=p.matcher(phrase);
while(m.find()) {
            System.out.println(m.group(0).replace("\n", "\\n").replace("\r", "\\r"));
} // .replace("\n", "\\n").replace("\r", "\\r") is only for demo

输出:

Heres is one line
\r\n
and another
\r
and another one
\n
all with different line ending chars

请参阅online Java demo .

\\V+|\\v+ 模式匹配除垂直空白之外的 1 个以上字符或 1 个以上垂直空白。

关于java - 正则表达式拆分 - 但包括换行符 - 包括 CR LF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49794785/

相关文章:

java - NIO:写入的字节永远不会到达接收者

regex - grep 通过显式文件列表

javascript - 为我的特定代码编写正则表达式

货币金额的正则表达式,D 表示负数,C 表示正数

java - Hibernate问题-映射ArrayList

java - 模拟时递归调用系统

java - 通过创建相同的包名来访问包访问成员

javascript - 对数组中的每个元素执行异步函数?

python 3 : values of a list change when it enters a for loop

c++ - for循环中的数组加法