C# - 在没有正则表达式的 .Net Framework 中,字符串替换为忽略大小写和整个单词

C# - String replace with Ignore Case as Well as Whole Word Only in .Net Framework without Regex

正则表达式没有正确替换特殊字符。所以任何替代或 修复此方法的代码。

直到现在我一直在使用正则表达式中的这种方法来替换

public static string Replace(this string s,string word ,string by ,bool IgnoreCase,bool WholeWord)
    {
        RegexOptions regexOptions = RegexOptions.None;
        if (IgnoreCase) regexOptions = RegexOptions.IgnoreCase;
        if (WholeWord) word = @"\b" + Regex.Escape(word) + @"\b";
        return Regex.Replace(s, word, by, regexOptions);
    }

我有一个字符串

string str = "Apple , Mango , Banana.";

如果我替换

str = str.Replace("apple", "Apples", true, true);

结果

Apples, Mango, Banana.

它适用于任何字母或数字,但不适用于非字母数字,如逗号 (,)、点 (.) 和其他 @、#、$、 ",:

例子

str = str.Replace(",", " and ", true, true); 

它什么也没做。

另一个例子我有字符串“She is Mari and she is Marijane.”; 如果我想将 Mari 替换为 Mira 正常替换将同时替换 Mari 和 Marijane 有的地方Mari在开头,有的地方在结尾用句号(.)连接,有时用逗号连接。

注意:我需要 IgnoreCase 和 WholeWord 作为 bool

已经有一些例子了,但是 none 可以组合(IgnoreCase 和 WholeWord),我需要 .Net Framework 4.8(它使用 C# 7.3 或更低版本)

所以请有人能在这种情况下帮助我

提前致谢,抱歉我的英语不好

我可以在不使用所谓的 Regex 或第三方包的情况下回答旧版本 .NET Frameworks 的问题

只需使用这些代码。

public static string Replace(this string s, string word, string by, StringComparison stringComparison, bool WholeWord)
    {
        s = s + " ";
        int wordSt;
        StringBuilder sb = new StringBuilder();
        while (s.IndexOf(word, stringComparison) > -1)
        {
            wordSt = s.IndexOf(word, stringComparison);
            if (!WholeWord || ((wordSt == 0 || !Char.IsLetterOrDigit(char.Parse(s.Substring(wordSt - 1, 1)))) && !Char.IsLetterOrDigit(char.Parse(s.Substring(wordSt + word.Length, 1)))))
            {
                sb.Append(s.Substring(0, wordSt) + by);
            }
            else
            {
                sb.Append(s.Substring(0, wordSt + word.Length));
            }
            s = s.Substring(wordSt + word.Length);
        }
        sb.Append(s);
        return sb.ToString().Substring(0, sb.Length - 1);
    }

如果你想要 StringComparison 作为 bool 然后添加这个

public static string Replace(this string s, string word, string by, bool IgnoreCase, bool WholeWord)
    {
        StringComparison stringComparison = StringComparison.Ordinal;
        if (IgnoreCase) stringComparison = StringComparison.OrdinalIgnoreCase;
        return s.Replace(word, by, stringComparison, WholeWord);
    }

您可以保留两者或合并它们。一切由你决定。