我有一个看似简单的情况,我需要在换行符上分割字符串序列(在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/