我有一个很长的字符串,其中包含  ,<p> </p> and <br> .我想从所有这些标签和空格中清除我的字符串。如何使用 String.Replace() 方法完成。我现在正在单独做,它正在工作,但有没有办法立即完成,没有 replace() 方法。
String.Replace(" ","").Replace("<p>","").Replace("<br>","")
它给我干净的代码,但我正在寻找一个通用的解决方案,这意味着如果我有更多的标签(10 到 20 个)要过滤,那么如何有效地进行过滤。
请您参考如下方法:
您可以构造一个由所有要替换的标签组成的正则表达式交替模式,例如 tag1|tag2,并使用 Regex.Replace method .您应该转义它们以防止任何字符被错误地解释为正则表达式元字符。
例如:
string input = "<p>Hello, World<br>Foo<br>Bar</p>";
string[] replaceItems = { "<p>", " ", "<br>" };
if (replaceItems.Length > 0)
{
string pattern =
String.Join("|", replaceItems.Select(s => Regex.Escape(s)).ToArray());
string result = Regex.Replace(input, pattern, String.Empty);
Console.WriteLine(result);
}
else
{
// nothing to replace
Console.WriteLine(input);
}
如果您需要替换不区分大小写,请使用 RegexOptions.IgnoreCase 选项:Regex.Replace(input, pattern, "", RegexOptions.IgnoreCase).
在 .NET 4.0 中,您可以放弃 ToArray() 调用。
