gpt4 book ai didi

c# - 进行字符串搜索和替换的最佳方法

转载 作者:太空宇宙 更新时间:2023-11-03 14:35:42 27 4
gpt4 key购买 nike

我需要编写一些代码来对字符串中的特定关键字执行 HTML 突出显示。

如果我有逗号分隔的字符串列表,我想搜索并替换列表中每个条目的另一个字符串。最有效的方法是什么?

我目前正在使用拆分,然后是 foreach 和 Regex.Match。例如:

string wordsToCheck = "this", "the", "and";
String listArray[] = wordsToCheck.Split(',');
string contentToReplace = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.";

foreach (string word in listArray)
{
if (Regex.Match(contentToReplace, word + "\\s+", RegexOptions.IgnoreCase).Success)
{
return Regex.Replace(contentToReplace , word + "\\s+", String.Format("<span style=\"background-color:yellow;\">{0}</span> ", word), RegexOptions.IgnoreCase);
}
}

我不确定这是最有效的方法,因为要检查的单词列表可能会很长,而且上面的代码可能是搜索和替换一堆内容的循环的一部分。

最佳答案

如果 wordsToCheck 可以被用户修改,请不要这样做!

您的方法在没有正则表达式的情况下也能完美运行。只需执行一个普通的 String.Replace。

如果输入是安全的,您还可以对所有关键字使用一个正则表达式,例如

return Regex.Replace(contentToReplace, "(this|the|and)", String.Format("<span style=\"background-color:yellow;\">{0}</span> ", word), RegexOptions.IgnoreCase);

其中“this|the|and”只是 wordsToCheck,其中逗号替换为竖线“|”。

顺便说一句,您可能希望直接将列表关键字作为正则表达式而不是逗号分隔列表。这将为您提供更大的灵 active 。

关于c# - 进行字符串搜索和替换的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1185223/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com