c# - 基于模式的更智能的字符串替换

标签 c# regex

我有一个看起来像这样的字符串:

string1 + \t\t\t\t\t\t\t + string2

string1 可以是任何内容,string2 可以是以下之一:Display、Search、Fee。对于转义字符,有时我得到 10 个,有时我得到 5 个,有时我得到一些数量 N ... 我只希望在 string1string2.

我目前拥有的:

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");

如果您只想删除紧随 DisplayFeeSearch 之一的额外标签,请使用

string newLine = Regex.Replace(line, @"\t{2,}(?=Display|Fee|Search)", "\t");

关于c# - 基于模式的更智能的字符串替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27154431/

相关文章:

javascript - 使用正则表达式在 JavaScript 中屏蔽日期的最后两位数字

c# - 嵌套 for 循环 : giving concatenated result

c# - 如何获取数据计数并使用 SQL 对其进行分类?

javascript - 当字符串包含特殊字符时,正则表达式查询速度变慢

php - 使用 preg_replace 替换 php 中所有出现的地方

php - 正则表达式取值在括号 "()"之间?

c# - 让 Monogame 内容管道与 Windows 8 中的 Visual Studio 2013 一起工作

c# - 在 Entity Framework 代码优先迁移中删除移动的属性

c# - 使用LINQ删除记录时出错

regex - 如果第二行包含与第一行相同的匹配项,我如何打印 2 行?