如何仅搜索和替换完全匹配的字符串

Dar*_*ana 10 c#

我需要搜索一个字符串并替换某个字符串

例如:搜索字符串"将附加字符串添加到文本框".将"添加"替换为"插入"

输出预期="将附加字符串插入文本框"

如果使用string s ="Add additional String to text box".replace("Add","Insert");

输出结果="将插入字符串插入文本框"

有没有人有想法让这个工作给出预期的输出?

谢谢!

sa_*_*213 16

您可以使用Regex执行此操作:

扩展方法示例:

public static class StringExtensions
{
    public static string SafeReplace(this string input, string find, string replace, bool matchWholeWord)
    {
        string textToFind = matchWholeWord ? string.Format(@"\b{0}\b", find) : find;
        return Regex.Replace(input, textToFind, replace);
    }
}
Run Code Online (Sandbox Code Playgroud)

用法:

  string text = "Add Additional String to text box";
  string result = text.SafeReplace("Add", "Insert", true);
Run Code Online (Sandbox Code Playgroud)

结果:"将附加字符串插入文本框"

  • 如果我需要替换以 @ 开头的单词,则此解决方案不起作用。在这里小提琴 https://dotnetfiddle.net/9kgW4h 我怎样才能让它在这种情况下工作。 (2认同)

Xia*_*Mao 5

string pattern = @"\bAdd\b";
string input = "Add Additional String to text box";
string result = Regex.Replace(input, pattern, "Insert", RegexOptions.None);  
Run Code Online (Sandbox Code Playgroud)

“\bAdd\b”确保它将匹配不属于其他单词的“Add”。希望它有帮助。