如何搜索和替换只有精确匹配的字符串 [英] How to search and replace exact matching strings only

查看:110
本文介绍了如何搜索和替换只有精确匹配的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在一个字符串搜索和替换某些字符串

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"

这篇关于如何搜索和替换只有精确匹配的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆