Java 正则表达式拆分-但包括新行字符-包括CR LF
我有一个看似简单的情况,我需要在换行符上拆分字符串序列(在Java中),但我需要输出中包含的新行字符(应用程序的另一部分需要这些字符)以及原始值,而不仅仅是任何新行字符) 下面的代码有效,但不包括CRLF(\r\n)。仅包含其中一个字符。如果我重写正则表达式模式以仅包含字符((?您可以改用匹配方法):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
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