Java 用空格分隔字符串,但在拆分数组中保留换行符
我试图在Java中拆分字符串,但将换行符保留为数组中的元素 例如,输入:Java 用空格分隔字符串,但在拆分数组中保留换行符,java,arrays,regex,string,Java,Arrays,Regex,String,我试图在Java中拆分字符串,但将换行符保留为数组中的元素 例如,输入:“Hello\n\n\nworld!” 我希望输出为:[“Hello”、“\n”、“\n”、“\n”、“world”、“!”] 我现在使用的正则表达式是: String[]parsed=input.split(“+|”(?=\\p{Punct})|)(?您可以首先将所有\n替换为\n(换行符和空格),然后对空格字符进行简单拆分 String input = "Hello \n\n\nworld!"; Stri
“Hello\n\n\nworld!”
我希望输出为:[“Hello”、“\n”、“\n”、“\n”、“world”、“!”]
我现在使用的正则表达式是:String[]parsed=input.split(“+|”(?=\\p{Punct})|)(?您可以首先将所有\n
替换为\n
(换行符和空格),然后对空格字符进行简单拆分
String input = "Hello \n\n\nworld!";
String replacement = input.replace("\n", "\n ");
String[] result = replacement.split(" ");
- 输入:
“你好\n\n\nworld!”
- 替换:
“你好\n\n\n世界!”
- 结果:
[“你好”、“\n”、“\n”、“\n”、“世界!”]
注意:我的示例不处理最后一个感叹号,但您似乎已经知道如何处理它。诀窍是在每个“\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})");
String line=“你好\n\n\n世界!”;
line=line.replaceAll(“\n”,“\n”);//这里我们将所有“\n”替换为“\n”
String[]items=line.split(“+|(?=\\p{Punct})|(?使用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));
}
String str=“你好\n\n\n世界!”;
List myList=new ArrayList();
Pattern pat=Pattern.compile(“\\w+\\H”);
匹配器m=匹配器(str);
while(m.find()){
myList.add(m.group(0));
}
如果使用Java 7,请将\\H
更改为[\\S\\n]
请注意,使用这种方法,您可以获得一个更易于编写和编辑的模式,因为您不需要使用lookarounds。使用find方法而不是split。与使用lookarounds相比,定义所需的项更容易。我猜结果如下:[“Hello”、“\n”、“\n”、“\n”、“\n”、“world!”]这是一个简单但优雅的解决方案,我不敢相信我自己没有想到!非常感谢。@Alynchos别担心。这很正常:当我们编写代码时,有时我们都会陷入细节。但是当其他人看到我们的代码时,他们会对问题有一个全新的、不带偏见的看法。