我需要搜索一个字符串并替换某个字符串
例如:搜索字符串"将附加字符串添加到文本框".将"添加"替换为"插入"
输出预期="将附加字符串插入文本框"
如果使用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)
结果:"将附加字符串插入文本框"
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”。希望它有帮助。