英文:
Delete empty spaces in a String without removing linebreaks
问题
以下是翻译好的内容:
我在一个txt
文件中有一列字符串
string1,
string2,
string3,
string4,
我想要删除string3
txtData = txtData.replace("string3,", "");
string1,
string2,
string4,
我不希望有空白处,所以我进行了以下操作
txtData = txtData.replace("\n", "");
但结果变成了这样
string1,string2,string4
我需要的是
string1,
string2,
string4,
英文:
I have a list of strings in a txt
file
string1,
string2,
string3,
string4,
I want to delete string3
txtData = txtData.replace("string3,", "");
string1,
string2,
string4,
I don't want that empty space there so I do this
txtData = txtData.replace("\n", "");
but that does this instead
string1,string2,string4
I need this
string1,
string2,
string4,
how?
答案1
得分: 2
合并您尝试过的两个方法:
txtData = txtData.replace("string3,\n", "");
如果您还希望此方法适用于位于文件末尾的情况,并且可能后面跟着换行符:
txtData = txtData.replaceAll("(?m)string3,$", "");
这是一个正则表达式,用于匹配行尾($
表示行尾,在多行模式下有效。(?m)
开启多行模式)。
英文:
Combine the two things you tried:
txtData = txtData.replace("string3,\n", "");
If you also want this to work if string3,
is at the end of the file and may or may not be followed by a newline:
txtData = txtData.replaceAll("(?m)string3,$", "");
That's a regular expression that matches 'end of line' ($
means: 'end of line', if in multiline mode. (?m)
turns on multiline mode).
答案2
得分: 1
你可以使用正则表达式来实现这个目的:
String str =
"string1,\n" +
"string2,\n" +
"string3,\n" +
"string4,";
// 移除字面上的 "string3," 及其后可能存在的空白字符
String str2 = str.replaceAll("string3,\\s*", "");
System.out.println(str2);
输出:
string1,
string2,
string4,
英文:
You can use regular expressions for this purpose:
String str =
"string1,\n" +
"string2,\n" +
"string3,\n" +
"string4,";
// remove literal "string3," and trailing
// whitespace characters after it, if present
String str2 = str.replaceAll("string3,\\s*","");
System.out.println(str2);
Output:
string1,
string2,
string4,
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论