Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/355.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 正则表达式拆分-但包括新行字符-包括CR LF_Java_Arrays_Regex_String - Fatal编程技术网

Java 正则表达式拆分-但包括新行字符-包括CR LF

Java 正则表达式拆分-但包括新行字符-包括CR LF,java,arrays,regex,string,Java,Arrays,Regex,String,我有一个看似简单的情况,我需要在换行符上拆分字符串序列(在Java中),但我需要输出中包含的新行字符(应用程序的另一部分需要这些字符)以及原始值,而不仅仅是任何新行字符) 下面的代码有效,但不包括CRLF(\r\n)。仅包含其中一个字符。如果我重写正则表达式模式以仅包含字符((?您可以改用匹配方法): String phrase = "Heres is one line\r\n" + "and another\r" + "and a

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

下面的代码有效,但不包括CRLF(\r\n)。仅包含其中一个字符。如果我重写正则表达式模式以仅包含字符((?您可以改用匹配方法):

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

\\V+|\\V+
模式匹配1+字符而不是垂直空格或1+垂直空格

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