如何搜索和替换只有精确匹配的字符串
问题描述:
我需要在一个字符串搜索和替换某些字符串
I need to search in a string and replace a certain string
例如:搜索字符串添加附加字符串文本框中输入。
替换添加与插入
Ex: Search String "Add Additional String to text box". Replace "Add" with "Insert"
总产值有望=插入附加字符串文本框中输入
Output expected = "Insert Additional String to text box"
如果您使用字符串s =添加附加字符串文本框中输入.replace(添加,插入);
If you use string s="Add Additional String to text box".replace("Add","Insert");
输出结果=插入Insertitional字符串文本框中输入
Output result = "Insert Insertitional String to text box"
有任何人有想法,让这工作,得到所需的输出?
Have anyone got ideas to get this working to give the expected output?
感谢您!
答
您可以使用正则表达式来做到这一点:
You can use Regex to do this:
扩展方法例如:
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);
}
}
用法:
Usage:
string text = "Add Additional String to text box";
string result = text.SafeReplace("Add", "Insert", true);
结果是:插入附加字符串文本框中输入
result: "Insert Additional String to text box"