繁体   English   中英

用空格分隔字符串,但在分割数组中保留换行符

[英]Separate string by whitespace, but keep newlines in split array

我正在尝试在Java中拆分字符串,但将换行符保留为数组中的元素

例如,输入: "Hello \\n\\n\\nworld!"

我希望输出为: ["Hello", "\\n", "\\n", "\\n", "world", "!"]

我现在使用的正则表达式是这样的:
String[] parsed = input.split(" +|(?=\\\\p{Punct})|(?<=\\\\p{Punct})");

这让我得到了我想要的标点符号分隔,但它的输出看起来像这样:
["Hello", "\\n\\n\\nworld", "!"]

有没有办法解开Java中的换行符?

诀窍是在每个“\\ n”之后添加空格,然后应用你的正则表达式。

    String line = "Hello \n\n\nworld!";
    line = line.replaceAll("\n", "\n "); // here we replace all "\n" to "\n "
    String[] items = line.split(" +|(?=\\p{Punct})|(?<=\\p{Punct})");   

or shorter version:

    String line = "Hello \n\n\nworld!";
    String[] items = line.replaceAll("\n", "\n ").split(" +|(?=\\p{Punct})|(?<=\\p{Punct})");  

因此,在这种情况下,结果是:[“你好”,“\\ n”,“\\ n”,“\\ n”,“世界”,“!”]

您可以先用\\n (换行符和空格)替换所有\\n ,然后对空格字符进行简单拆分。

    String input = "Hello \n\n\nworld!";
    String replacement = input.replace("\n", "\n ");
    String[] result = replacement.split(" ");
  • 输入: "Hello \\n\\n\\nworld!"
  • 替换: "Hello \\n \\n \\n world!"
  • 结果: ["Hello", "\\n", "\\n", "\\n", "world!"]

注意:我的示例没有处理最终的感叹号 - 但似乎您已经知道如何处理它。

使用find方法可以简化操作:

String str = "Hello \n\n\nworld!";
List<String> myList = new ArrayList<String>();

Pattern pat = Pattern.compile("\\w+|\\H");
Matcher m = pat.matcher(str);

while (m.find()) {
    myList.add(m.group(0));
}

如果使用Java 7,请将\\\\H更改为[\\\\S\\\\n]

请注意,使用此方法,您可以更轻松地编写和编辑模式,因为您不需要使用外观。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM