繁体   English   中英

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

[英]How to search and replace exact matching strings only

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

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

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

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

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

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

谢谢!

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

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

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

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

回答:
“如果我需要替换一个以@开头的单词,这个解决方案不起作用。在这里fnet这个dotnetfiddle.net/9kgW4h如何在这种情况下使用它。 - Frenz于17年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);
} 

使用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方法应该足够了。

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

// 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();

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

//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();

    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM