c# - 在 stringbuilder 中搜索字符串并替换整行 C#

标签 c# regex string stringbuilder

我正在使用 C#,我有一个 stringbuilder sb,它有一些行包含由制表符分隔的字符串,如下所示:

1.14332    534335    4452435435
1.32332    534535    4354535435
1.34432    524335    4353235435
1.44332    534435    4352235435
.
.
.

我想做的是在这个字符串生成器中搜索一个字符串,如果找到这个字符串,那么我想用另一个新字符串替换包含这个字符串的整行。例如,如果我要搜索的词是 1.32332 那么这一行 1.32332 534535 4354535435 sb 中的 将替换为新的子字符串,例如 1.32332 664535 1154536665。有什么建议吗?

最佳答案

在我看来你想要像这样格式化一个模式:

String.Format(@"{0}\s*?\d+\s*?\d+", searchValue)

因为您要查找的行的开头可能会有所不同。在您的示例案例中,格式化后的模式如下所示:

@"1\.32332\s*?\d+\s*?\d+"

这将找到您感兴趣的行进行替换。话虽如此,请尝试一下:

StringBuilder sb = new StringBuilder();
sb.AppendLine("1.14332    534335    4452435435");
sb.AppendLine("1.32332    534535    4354535435");
sb.AppendLine("1.34432    524335    4353235435");
sb.AppendLine("1.44332    534435    4352235435");

Console.WriteLine("Before: ");
Console.WriteLine(sb);

// Have to escape the decimal point to be part of the regex pattern
string searchValue = @"1\.32332";
string replaceValue = "1.32332    664535    1154536665";
Match match = Regex.Match(sb.ToString(), String.Format(@"{0}\s*?\d+\s*?\\d+", searchValue));
if (match.Success)
{
    sb.Replace(match.Value, replaceValue);
}

Console.WriteLine("After: ");
Console.WriteLine(sb);

结果:

Before:
1.14332    534335    4452435435
1.32332    534535    4354535435
1.34432    524335    4353235435
1.44332    534435    4352235435

After:
1.14332    534335    4452435435
1.32332    664535    1154536665
1.34432    524335    4353235435
1.44332    534435    4352235435

关于c# - 在 stringbuilder 中搜索字符串并替换整行 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31656477/

相关文章:

javascript - 为什么这会返回一个数字?

c# - 从 .net 调用存储过程

c# - 将字符串转换为没有时间的日期

regex - 在文件开头插入一个新行

c - 如何在 C 中分配新的字符串值

string - 将日期格式从 DD.MM.YYYY 转换为 YYYY-MM-DD

c# - PGP 加密和解密

c# - Xamarin Forms PopAsync 崩溃

regex - 使用正则表达式检测序列

PHP 正则表达式 - 检测未闭合的括号