删除字符串中的空格,但不要删除换行符。

huangapple go评论81阅读模式
英文:

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,

huangapple
  • 本文由 发表于 2020年10月24日 08:45:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/64508904.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定