Skip to main content
 首页 » 编程设计

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

2024年02月05日23wayfarer

我正在使用 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