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

时间:2012-12-14 00:03:02

标签: c#

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

  

Ex:搜索字符串“将附加字符串添加到文本框”。       将“添加”替换为“插入”

     

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

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

  

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

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

谢谢!

6 个答案:

答案 0 :(得分:15)

您可以使用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);
    }
}

用法:

  string text = "Add Additional String to text box";
  string result = text.SafeReplace("Add", "Insert", true);

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

答案 1 :(得分:3)

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

“\ bAdd \ b”确保它匹配“Add”,这不是其他单词的一部分。 希望它有用。

答案 2 :(得分:0)

使用string.Replace(string old, string replacement)方法。

 string input = "Add Additional String to text box";
 string output = input.replace("Add ", "Insert ");

 output == "Insert Additional String to text box" // true

如果您需要更大的灵活性,请使用RegEx,但由于您要替换精确的字符串,因此string.replace方法应该足够了。

答案 3 :(得分:0)

如果你只想替换一个完整的单词,而不是替换另一个单词中的对应单词,你可以这样做:

// add a leading and tail space
string tmp = " " + "Add Additional String to text box"+ " ";
// replace the word you want, while adding a lead and tail space, and then Trim
tmp = tmp.Replace(" Add ", " Insert ").Trim();

现在无法测试,但这可能有用。

答案 4 :(得分:0)

//Find and Replace A word in c#
public static class Program
    {
        public static string Replace(this String str, char[] chars, string replacement)
        {
            StringBuilder output = new StringBuilder(str.Length);
            bool replace = false;
            if (chars.Length - 1 < 1)
            {
                for (int i = 0; i < str.Length; i++)
                {

                    char c = str[i];
                    replace = false;
                    //  int val = Regex.Matches(ch.ToString(), @"[a-zA-Z]").Count;


                    for (int j = 0; j < chars.Length; j++)
                    {
                        if (chars[j] == c)
                        {
                            replace = true;

                            break;

                        }

                    }

                    if (replace)
                        output.Append(replacement);
                    else
                        output.Append(c);
                }
            }
            else
            {

                int j = 0;
                int truecount = 0;
                    char c1 = '\0';
                    for (int k = 0; k < str.Length; k++)
                    {
                       c1 = str[k];

                        if (chars[j] == c1)
                        {
                            replace = true;
                            truecount ++;


                        }

                        else
                        {
                            truecount = 0;
                            replace = false;
                            j = 0;
                        }
                        if(truecount>0)
                        {
                            j++;
                        }

                        if (j > chars.Length-1)
                        {
                            j = 0;
                        }

                        if (truecount == chars.Length)
                        {
                            output.Remove(output.Length - chars.Length+1, chars.Length-1);
                           // output.Remove(4, 2);
                            if (replace)
                                output.Append(replacement);
                            else
                                output.Append(c1);
                        }
                        else
                        {
                            output.Append(c1);
                        }


                    }

            }


            return output.ToString();
        }


    static void Main(string[] args)
    {

        Console.WriteLine("Enter a word");
        string word = (Console.ReadLine());

        Console.WriteLine("Enter a word to find");
        string find = (Console.ReadLine());

        Console.WriteLine("Enter a word to Replace");
        string Rep = (Console.ReadLine());

        Console.WriteLine(Replace(word, find.ToCharArray(), Rep));
        Console.ReadLine();

    }

}

答案 5 :(得分:0)

答案:
“如果我需要替换以@开头的单词,那么该解决方案将不起作用。在这里,请在Fiddle dotnetfiddle.net/9kgW4h中进行操作。–在这种情况下,如何使它起作用。– Frenz,2017年1月16日,5:46”

可能的解决方案:

public static string SafeReplace(this string input, string find, string replace, bool matchWholeWord) {
    string searchString = find.StartsWith("@") ? $@"@\b{find.Substring(1)}\b" : $@"\b{find}\b"; 
    string textToFind = matchWholeWord ? searchString : find;
    return Regex.Replace(input, textToFind, replace);
} 
相关问题