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

时间:2018-04-12 10:58:27

标签: java arrays regex string

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

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

        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);
        }

1 个答案:

答案 0 :(得分:2)

您可以使用匹配方法:

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 +个字符。