我有一个看起来像这样的字符串:
string1
+ \t\t\t\t\t\t\t
+ string2
string1
可以是任何内容,string2
可以是以下之一:Display、Search、Fee。对于转义字符,有时我得到 10 个,有时我得到 5 个,有时我得到一些数量 N ... 我只希望在 string1
和 string2
.
我目前拥有的:
string newLine0 = line.Replace("\t\t\t\t\t\t\t\t\t\t\t\t\t\tDisplay", "\tDisplay");
string newline1 = newLine0.Replace("\t\tFee", "\tFee");
string newLine2 = newline1.Replace("\t\tSearch", "\tSearch");
string newLine3 = newLine2.Replace("\t\t\t\t\t\t\t\t\t\t\t\tDisplay", "\tDisplay");
string newLine4 = newLine3.Replace("\t\tDisplay", "\tDisplay");
有没有更好的方法来使用更清晰的代码和更少的变量来做到这一点?
最佳答案
似乎您可以简单地将多个 \t
的实例替换为单个 \t
:
string newLine = Regex.Replace(line, @"\t{2,}", "\t");
如果您只想删除紧随 Display
、Fee
或 Search
之一的额外标签,请使用
string newLine = Regex.Replace(line, @"\t{2,}(?=Display|Fee|Search)", "\t");
关于c# - 基于模式的更智能的字符串替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27154431/