有弦的替代品吗?替换不区分大小写吗?

时间:2021-11-19 19:25:23

I need to search a string and replace all occurrences of %FirstName% and %PolicyAmount% with a value pulled from a database. The problem is the capitalization of FirstName varies. That prevents me from using the String.Replace() method. I've seen web pages on the subject that suggest

我需要搜索一个字符串,并用从数据库中提取的值替换出现的所有%FirstName%和%PolicyAmount%。问题是名字的大小写不一样。这阻止我使用String.Replace()方法。我在网页上看到过关于这个主题的建议

Regex.Replace(strInput, strToken, strReplaceWith, RegexOptions.IgnoreCase);

However for some reason when I try and replace %PolicyAmount% with $0, the replacement never takes place. I assume that it has something to do with the dollar sign being a reserved character in regex.

然而,由于某些原因,当我尝试用$0替换%PolicyAmount%时,替换永远不会发生。我认为这与美元符号是regex中的保留字符有关。

Is there another method I can use that doesn't involve sanitizing the input to deal with regex special characters?

我还可以使用其他不涉及对输入进行消毒的方法来处理regex特殊字符吗?

14 个解决方案

#1


126  

From MSDN
$0 - "Substitutes the last substring matched by group number number (decimal)."

从MSDN $0—“替换最后一个由组号(decimal)匹配的子字符串。”

In .NET Regular expressions group 0 is always the entire match. For a literal $ you need to

在。net中,正则表达式组0总是整个匹配。你需要花一大笔钱

string value = Regex.Replace("%PolicyAmount%", "%PolicyAmount%", @"$$0", RegexOptions.IgnoreCase);

#2


289  

Seems like string.Replace should have an overload that takes a StringComparison argument. Since it doesn't, you could try something like this:

似乎是字符串。Replace应该具有一个接受StringComparison参数的重载。既然没有,你可以试试这样的方法:

public static string ReplaceString(string str, string oldValue, string newValue, StringComparison comparison)
{
    StringBuilder sb = new StringBuilder();

    int previousIndex = 0;
    int index = str.IndexOf(oldValue, comparison);
    while (index != -1)
    {
        sb.Append(str.Substring(previousIndex, index - previousIndex));
        sb.Append(newValue);
        index += oldValue.Length;

        previousIndex = index;
        index = str.IndexOf(oldValue, index, comparison);
    }
    sb.Append(str.Substring(previousIndex));

    return sb.ToString();
}

#3


31  

Kind of a confusing group of answers, in part because the title of the question is actually much larger than the specific question being asked. After reading through, I'm not sure any answer is a few edits away from assimilating all the good stuff here, so I figured I'd try to sum.

这是一组令人困惑的答案,部分原因是这个问题的题目实际上比要问的具体问题要大得多。在通读之后,我不确定是否有任何答案可以帮助我吸收这里所有的好东西,所以我想我会试着总结一下。

Here's an extension method that I think avoids the pitfalls mentioned here and provides the most broadly applicable solution.

这里有一个扩展方法,我认为可以避免这里提到的缺陷,并提供最广泛适用的解决方案。

public static string ReplaceCaseInsensitiveFind(this string str, string findMe,
    string newValue)
{
    return Regex.Replace(str,
        Regex.Escape(findMe),
        Regex.Replace(newValue, "\\$[0-9]+", @"$$$0"),
        RegexOptions.IgnoreCase);
}

So...

所以…

  • This is an extension method @MarkRobinson
  • 这是一个扩展方法@MarkRobinson
  • This doesn't try to skip Regex @Helge (you really have to do byte-by-byte if you want to string sniff like this outside of Regex)
  • 这并不是要跳过Regex @Helge(如果您想在Regex之外像这样字符串嗅探,那么必须逐个字节地执行)
  • Passes @MichaelLiu 's excellent test case, "œ".ReplaceCaseInsensitiveFind("oe", ""), though he may have had a slightly different behavior in mind.
  • 通过@MichaelLiu优秀的测试用例,“œ”。replacecaseinsensivefind(“oe”,“oe”),尽管他心里可能有一点不同的行为。

Unfortunately, @HA 's comment that you have to Escape all three isn't correct. The initial value and newValue doesn't need to be.

不幸的是,@HA的评论说你必须要逃离这三种情况,这是不正确的。初始值和newValue不需要。

Note: You do, however, have to escape $s in the new value that you're inserting if they're part of what would appear to be a "captured value" marker. Thus the three dollar signs in the Regex.Replace inside the Regex.Replace [sic]. Without that, something like this breaks...

注意:但是,如果您要插入的新值中的$s是“捕获值”标记的一部分,那么您必须避免$s。因此,Regex中的3美元符号。在正则表达式替换。取代(原文如此)。没有它,像这样的东西就会断裂……

"This is HIS fork, hIs spoon, hissssssss knife.".ReplaceCaseInsensitiveFind("his", @"he$0r")

“这是他的叉子,他的汤匙,他的刀子。”ReplaceCaseInsensitiveFind(“他”@”他$ 0 r”)

Here's the error:

这是一个错误:

An unhandled exception of type 'System.ArgumentException' occurred in System.dll

Additional information: parsing "The\hisr\ is\ he\HISr\ fork,\ he\hIsr\ spoon,\ he\hisrsssssss\ knife\." - Unrecognized escape sequence \h.

Tell you what, I know folks that are comfortable with Regex feel like their use avoids errors, but I'm often still partial to byte sniffing strings (but only after having read Spolsky on encodings) to be absolutely sure you're getting what you intended for important use cases. Reminds me of Crockford on "insecure regular expressions" a little. Too often we write regexps that allow what we want (if we're lucky), but unintentionally allow more in (eg, Is $10 really a valid "capture value" string in my newValue regexp, above?) because we weren't thoughtful enough. Both methods have value, and both encourage different types of unintentional errors. It's often easy to underestimate complexity.

告诉你吧,我知道熟悉Regex的人觉得他们的使用可以避免错误,但我通常仍然偏爱字节嗅探字符串(但只有在阅读了Spolsky关于编码的文章之后),以确保您得到了您希望用于重要用例的内容。这让我想起了克罗克福德的《不安全正则表达式》。我们经常编写regexp以允许我们想要的内容(如果幸运的话),但是无意中允许更多内容(例如,$10在我的newValue regexp中真的是有效的“捕获值”字符串吗?这两种方法都有价值,并且都鼓励不同类型的无意错误。通常很容易低估复杂性。

That weird $ escaping (and that Regex.Escape didn't escape captured value patterns like $0 as I would have expected in replacement values) drove me mad for a while. Programming Is Hard (c) 1842

那个奇怪的$ escape(还有那个Regex。Escape没有像我在替换值中预期的$0那样逃脱捕获的值模式)让我疯狂了一段时间。编程很难(c) 1842年

#4


30  

Here's an extension method. Not sure where I found it.

这是一个扩展方法。不知道在哪儿找到的。

public static class StringExtensions
{
    public static string Replace(this string originalString, string oldValue, string newValue, StringComparison comparisonType)
    {
        int startIndex = 0;
        while (true)
        {
            startIndex = originalString.IndexOf(oldValue, startIndex, comparisonType);
            if (startIndex == -1)
                break;

            originalString = originalString.Substring(0, startIndex) + newValue + originalString.Substring(startIndex + oldValue.Length);

            startIndex += newValue.Length;
        }

        return originalString;
    }

}

#5


30  

Seems the easiest method is simply to use the Replace method that ships with .Net and has been around since .Net 1.0:

似乎最简单的方法就是使用。net自带的替换方法,从。net 1.0开始就有了:

string res = Microsoft.VisualBasic.Strings.Replace(res, 
                                   "%PolicyAmount%", 
                                   "$0", 
                                   Compare: Microsoft.VisualBasic.CompareMethod.Text);

In order to use this method, you have to add a Reference to the Microsoft.VisualBasic assemblly. This assembly is a standard part of the .Net runtime, it is not an extra download or marked as obsolete.

为了使用这个方法,您必须添加一个对Microsoft的引用。VisualBasic组装。这个程序集是。net运行时的标准部分,它不是一个额外的下载或标记为过时。

#6


9  

    /// <summary>
    /// A case insenstive replace function.
    /// </summary>
    /// <param name="originalString">The string to examine.(HayStack)</param>
    /// <param name="oldValue">The value to replace.(Needle)</param>
    /// <param name="newValue">The new value to be inserted</param>
    /// <returns>A string</returns>
    public static string CaseInsenstiveReplace(string originalString, string oldValue, string newValue)
    {
        Regex regEx = new Regex(oldValue,
           RegexOptions.IgnoreCase | RegexOptions.Multiline);
        return regEx.Replace(originalString, newValue);
    }

#7


8  

Inspired by cfeduke's answer, I made this function which uses IndexOf to find the old value in the string and then replaces it with the new value. I used this in an SSIS script processing millions of rows, and the regex-method was way slower than this.

在cfeduke的回答的启发下,我创建了这个函数,它使用IndexOf查找字符串中的旧值,然后用新值替换它。我在一个SSIS脚本中使用这个方法处理了数百万行,而regex方法的速度比这个要慢。

public static string ReplaceCaseInsensitive(this string str, string oldValue, string newValue)
{
    int prevPos = 0;
    string retval = str;
    // find the first occurence of oldValue
    int pos = retval.IndexOf(oldValue, StringComparison.InvariantCultureIgnoreCase);

    while (pos > -1)
    {
        // remove oldValue from the string
        retval = retval.Remove(pos, oldValue.Length);

        // insert newValue in it's place
        retval = retval.Insert(pos, newValue);

        // check if oldValue is found further down
        prevPos = pos + newValue.Length;
        pos = retval.IndexOf(oldValue, prevPos, StringComparison.InvariantCultureIgnoreCase);
    }

    return retval;
}

#8


6  

Expanding on C. Dragon 76's popular answer by making his code into an extension that overloads the default Replace method.

扩展C. Dragon 76的流行答案,使他的代码扩展为重载默认替换方法的扩展。

public static class StringExtensions
{
    public static string Replace(this string str, string oldValue, string newValue, StringComparison comparison)
    {
        StringBuilder sb = new StringBuilder();

        int previousIndex = 0;
        int index = str.IndexOf(oldValue, comparison);
        while (index != -1)
        {
            sb.Append(str.Substring(previousIndex, index - previousIndex));
            sb.Append(newValue);
            index += oldValue.Length;

            previousIndex = index;
            index = str.IndexOf(oldValue, index, comparison);
        }
        sb.Append(str.Substring(previousIndex));
        return sb.ToString();
     }
}

#9


3  

Based on Jeff Reddy's answer, with some optimisations and validations:

根据Jeff Reddy的回答,进行一些优化和验证:

public static string Replace(string str, string oldValue, string newValue, StringComparison comparison)
{
    if (oldValue == null)
        throw new ArgumentNullException("oldValue");
    if (oldValue.Length == 0)
        throw new ArgumentException("String cannot be of zero length.", "oldValue");

    StringBuilder sb = null;

    int startIndex = 0;
    int foundIndex = str.IndexOf(oldValue, comparison);
    while (foundIndex != -1)
    {
        if (sb == null)
            sb = new StringBuilder(str.Length + (newValue != null ? Math.Max(0, 5 * (newValue.Length - oldValue.Length)) : 0));
        sb.Append(str, startIndex, foundIndex - startIndex);
        sb.Append(newValue);

        startIndex = foundIndex + oldValue.Length;
        foundIndex = str.IndexOf(oldValue, startIndex, comparison);
    }

    if (startIndex == 0)
        return str;
    sb.Append(str, startIndex, str.Length - startIndex);
    return sb.ToString();
}

#10


2  

a version similar to C. Dragon's, but for if you only need a single replacement:

类似c龙的版本,但如果你只需要一个替换:

int n = myText.IndexOf(oldValue, System.StringComparison.InvariantCultureIgnoreCase);
if (n >= 0)
{
    myText = myText.Substring(0, n)
        + newValue
        + myText.Substring(n + oldValue.Length);
}

#11


1  

Here is another option for executing Regex replacements, since not many people seem to notice the matches contain the location within the string:

这里是执行Regex替换的另一个选项,因为似乎没有多少人注意到匹配包含字符串中的位置:

    public static string ReplaceCaseInsensative( this string s, string oldValue, string newValue ) {
        var sb = new StringBuilder(s);
        int offset = oldValue.Length - newValue.Length;
        int matchNo = 0;
        foreach (Match match in Regex.Matches(s, Regex.Escape(oldValue), RegexOptions.IgnoreCase))
        {
            sb.Remove(match.Index - (offset * matchNo), match.Length).Insert(match.Index - (offset * matchNo), newValue);
            matchNo++;
        }
        return sb.ToString();
    }

#12


0  

Regex.Replace(strInput, strToken.Replace("$", "[$]"), strReplaceWith, RegexOptions.IgnoreCase);

#13


0  

The regular expression method should work. However what you can also do is lower case the string from the database, lower case the %variables% you have, and then locate the positions and lengths in the lower cased string from the database. Remember, positions in a string don't change just because its lower cased.

正则表达式方法应该有效。但是,您还可以做的是降低数据库中的字符串的大小写,降低您拥有的%variable %的大小写,然后从数据库中定位小写字符串中的位置和长度。记住,字符串中的位置不会因为小写而改变。

Then using a loop that goes in reverse (its easier, if you do not you will have to keep a running count of where later points move to) remove from your non-lower cased string from the database the %variables% by their position and length and insert the replacement values.

然后使用反向的循环(如果不这样做的话,就更容易)从数据库中删除非小写字符串%variable %的位置和长度,并插入替换值。

#14


0  

(Since everyone is taking a shot at this). Here's my version (with null checks, and correct input and replacement escaping) ** Inspired from around the internet and other versions:

(因为每个人都在尝试这个)。这是我的版本(用空检查,正确的输入和替换)**来自互联网和其他版本的启发:

using System;
using System.Text.RegularExpressions;

public static class MyExtensions {
    public static string ReplaceIgnoreCase(this string search, string find, string replace) {
        return Regex.Replace(search ?? "", Regex.Escape(find ?? ""), (replace ?? "").Replace("$", "$$"), RegexOptions.IgnoreCase);          
    }
}

Usage:

用法:

var result = "This is a test".ReplaceIgnoreCase("IS", "was");

#1


126  

From MSDN
$0 - "Substitutes the last substring matched by group number number (decimal)."

从MSDN $0—“替换最后一个由组号(decimal)匹配的子字符串。”

In .NET Regular expressions group 0 is always the entire match. For a literal $ you need to

在。net中,正则表达式组0总是整个匹配。你需要花一大笔钱

string value = Regex.Replace("%PolicyAmount%", "%PolicyAmount%", @"$$0", RegexOptions.IgnoreCase);

#2


289  

Seems like string.Replace should have an overload that takes a StringComparison argument. Since it doesn't, you could try something like this:

似乎是字符串。Replace应该具有一个接受StringComparison参数的重载。既然没有,你可以试试这样的方法:

public static string ReplaceString(string str, string oldValue, string newValue, StringComparison comparison)
{
    StringBuilder sb = new StringBuilder();

    int previousIndex = 0;
    int index = str.IndexOf(oldValue, comparison);
    while (index != -1)
    {
        sb.Append(str.Substring(previousIndex, index - previousIndex));
        sb.Append(newValue);
        index += oldValue.Length;

        previousIndex = index;
        index = str.IndexOf(oldValue, index, comparison);
    }
    sb.Append(str.Substring(previousIndex));

    return sb.ToString();
}

#3


31  

Kind of a confusing group of answers, in part because the title of the question is actually much larger than the specific question being asked. After reading through, I'm not sure any answer is a few edits away from assimilating all the good stuff here, so I figured I'd try to sum.

这是一组令人困惑的答案,部分原因是这个问题的题目实际上比要问的具体问题要大得多。在通读之后,我不确定是否有任何答案可以帮助我吸收这里所有的好东西,所以我想我会试着总结一下。

Here's an extension method that I think avoids the pitfalls mentioned here and provides the most broadly applicable solution.

这里有一个扩展方法,我认为可以避免这里提到的缺陷,并提供最广泛适用的解决方案。

public static string ReplaceCaseInsensitiveFind(this string str, string findMe,
    string newValue)
{
    return Regex.Replace(str,
        Regex.Escape(findMe),
        Regex.Replace(newValue, "\\$[0-9]+", @"$$$0"),
        RegexOptions.IgnoreCase);
}

So...

所以…

  • This is an extension method @MarkRobinson
  • 这是一个扩展方法@MarkRobinson
  • This doesn't try to skip Regex @Helge (you really have to do byte-by-byte if you want to string sniff like this outside of Regex)
  • 这并不是要跳过Regex @Helge(如果您想在Regex之外像这样字符串嗅探,那么必须逐个字节地执行)
  • Passes @MichaelLiu 's excellent test case, "œ".ReplaceCaseInsensitiveFind("oe", ""), though he may have had a slightly different behavior in mind.
  • 通过@MichaelLiu优秀的测试用例,“œ”。replacecaseinsensivefind(“oe”,“oe”),尽管他心里可能有一点不同的行为。

Unfortunately, @HA 's comment that you have to Escape all three isn't correct. The initial value and newValue doesn't need to be.

不幸的是,@HA的评论说你必须要逃离这三种情况,这是不正确的。初始值和newValue不需要。

Note: You do, however, have to escape $s in the new value that you're inserting if they're part of what would appear to be a "captured value" marker. Thus the three dollar signs in the Regex.Replace inside the Regex.Replace [sic]. Without that, something like this breaks...

注意:但是,如果您要插入的新值中的$s是“捕获值”标记的一部分,那么您必须避免$s。因此,Regex中的3美元符号。在正则表达式替换。取代(原文如此)。没有它,像这样的东西就会断裂……

"This is HIS fork, hIs spoon, hissssssss knife.".ReplaceCaseInsensitiveFind("his", @"he$0r")

“这是他的叉子,他的汤匙,他的刀子。”ReplaceCaseInsensitiveFind(“他”@”他$ 0 r”)

Here's the error:

这是一个错误:

An unhandled exception of type 'System.ArgumentException' occurred in System.dll

Additional information: parsing "The\hisr\ is\ he\HISr\ fork,\ he\hIsr\ spoon,\ he\hisrsssssss\ knife\." - Unrecognized escape sequence \h.

Tell you what, I know folks that are comfortable with Regex feel like their use avoids errors, but I'm often still partial to byte sniffing strings (but only after having read Spolsky on encodings) to be absolutely sure you're getting what you intended for important use cases. Reminds me of Crockford on "insecure regular expressions" a little. Too often we write regexps that allow what we want (if we're lucky), but unintentionally allow more in (eg, Is $10 really a valid "capture value" string in my newValue regexp, above?) because we weren't thoughtful enough. Both methods have value, and both encourage different types of unintentional errors. It's often easy to underestimate complexity.

告诉你吧,我知道熟悉Regex的人觉得他们的使用可以避免错误,但我通常仍然偏爱字节嗅探字符串(但只有在阅读了Spolsky关于编码的文章之后),以确保您得到了您希望用于重要用例的内容。这让我想起了克罗克福德的《不安全正则表达式》。我们经常编写regexp以允许我们想要的内容(如果幸运的话),但是无意中允许更多内容(例如,$10在我的newValue regexp中真的是有效的“捕获值”字符串吗?这两种方法都有价值,并且都鼓励不同类型的无意错误。通常很容易低估复杂性。

That weird $ escaping (and that Regex.Escape didn't escape captured value patterns like $0 as I would have expected in replacement values) drove me mad for a while. Programming Is Hard (c) 1842

那个奇怪的$ escape(还有那个Regex。Escape没有像我在替换值中预期的$0那样逃脱捕获的值模式)让我疯狂了一段时间。编程很难(c) 1842年

#4


30  

Here's an extension method. Not sure where I found it.

这是一个扩展方法。不知道在哪儿找到的。

public static class StringExtensions
{
    public static string Replace(this string originalString, string oldValue, string newValue, StringComparison comparisonType)
    {
        int startIndex = 0;
        while (true)
        {
            startIndex = originalString.IndexOf(oldValue, startIndex, comparisonType);
            if (startIndex == -1)
                break;

            originalString = originalString.Substring(0, startIndex) + newValue + originalString.Substring(startIndex + oldValue.Length);

            startIndex += newValue.Length;
        }

        return originalString;
    }

}

#5


30  

Seems the easiest method is simply to use the Replace method that ships with .Net and has been around since .Net 1.0:

似乎最简单的方法就是使用。net自带的替换方法,从。net 1.0开始就有了:

string res = Microsoft.VisualBasic.Strings.Replace(res, 
                                   "%PolicyAmount%", 
                                   "$0", 
                                   Compare: Microsoft.VisualBasic.CompareMethod.Text);

In order to use this method, you have to add a Reference to the Microsoft.VisualBasic assemblly. This assembly is a standard part of the .Net runtime, it is not an extra download or marked as obsolete.

为了使用这个方法,您必须添加一个对Microsoft的引用。VisualBasic组装。这个程序集是。net运行时的标准部分,它不是一个额外的下载或标记为过时。

#6


9  

    /// <summary>
    /// A case insenstive replace function.
    /// </summary>
    /// <param name="originalString">The string to examine.(HayStack)</param>
    /// <param name="oldValue">The value to replace.(Needle)</param>
    /// <param name="newValue">The new value to be inserted</param>
    /// <returns>A string</returns>
    public static string CaseInsenstiveReplace(string originalString, string oldValue, string newValue)
    {
        Regex regEx = new Regex(oldValue,
           RegexOptions.IgnoreCase | RegexOptions.Multiline);
        return regEx.Replace(originalString, newValue);
    }

#7


8  

Inspired by cfeduke's answer, I made this function which uses IndexOf to find the old value in the string and then replaces it with the new value. I used this in an SSIS script processing millions of rows, and the regex-method was way slower than this.

在cfeduke的回答的启发下,我创建了这个函数,它使用IndexOf查找字符串中的旧值,然后用新值替换它。我在一个SSIS脚本中使用这个方法处理了数百万行,而regex方法的速度比这个要慢。

public static string ReplaceCaseInsensitive(this string str, string oldValue, string newValue)
{
    int prevPos = 0;
    string retval = str;
    // find the first occurence of oldValue
    int pos = retval.IndexOf(oldValue, StringComparison.InvariantCultureIgnoreCase);

    while (pos > -1)
    {
        // remove oldValue from the string
        retval = retval.Remove(pos, oldValue.Length);

        // insert newValue in it's place
        retval = retval.Insert(pos, newValue);

        // check if oldValue is found further down
        prevPos = pos + newValue.Length;
        pos = retval.IndexOf(oldValue, prevPos, StringComparison.InvariantCultureIgnoreCase);
    }

    return retval;
}

#8


6  

Expanding on C. Dragon 76's popular answer by making his code into an extension that overloads the default Replace method.

扩展C. Dragon 76的流行答案,使他的代码扩展为重载默认替换方法的扩展。

public static class StringExtensions
{
    public static string Replace(this string str, string oldValue, string newValue, StringComparison comparison)
    {
        StringBuilder sb = new StringBuilder();

        int previousIndex = 0;
        int index = str.IndexOf(oldValue, comparison);
        while (index != -1)
        {
            sb.Append(str.Substring(previousIndex, index - previousIndex));
            sb.Append(newValue);
            index += oldValue.Length;

            previousIndex = index;
            index = str.IndexOf(oldValue, index, comparison);
        }
        sb.Append(str.Substring(previousIndex));
        return sb.ToString();
     }
}

#9


3  

Based on Jeff Reddy's answer, with some optimisations and validations:

根据Jeff Reddy的回答,进行一些优化和验证:

public static string Replace(string str, string oldValue, string newValue, StringComparison comparison)
{
    if (oldValue == null)
        throw new ArgumentNullException("oldValue");
    if (oldValue.Length == 0)
        throw new ArgumentException("String cannot be of zero length.", "oldValue");

    StringBuilder sb = null;

    int startIndex = 0;
    int foundIndex = str.IndexOf(oldValue, comparison);
    while (foundIndex != -1)
    {
        if (sb == null)
            sb = new StringBuilder(str.Length + (newValue != null ? Math.Max(0, 5 * (newValue.Length - oldValue.Length)) : 0));
        sb.Append(str, startIndex, foundIndex - startIndex);
        sb.Append(newValue);

        startIndex = foundIndex + oldValue.Length;
        foundIndex = str.IndexOf(oldValue, startIndex, comparison);
    }

    if (startIndex == 0)
        return str;
    sb.Append(str, startIndex, str.Length - startIndex);
    return sb.ToString();
}

#10


2  

a version similar to C. Dragon's, but for if you only need a single replacement:

类似c龙的版本,但如果你只需要一个替换:

int n = myText.IndexOf(oldValue, System.StringComparison.InvariantCultureIgnoreCase);
if (n >= 0)
{
    myText = myText.Substring(0, n)
        + newValue
        + myText.Substring(n + oldValue.Length);
}

#11


1  

Here is another option for executing Regex replacements, since not many people seem to notice the matches contain the location within the string:

这里是执行Regex替换的另一个选项,因为似乎没有多少人注意到匹配包含字符串中的位置:

    public static string ReplaceCaseInsensative( this string s, string oldValue, string newValue ) {
        var sb = new StringBuilder(s);
        int offset = oldValue.Length - newValue.Length;
        int matchNo = 0;
        foreach (Match match in Regex.Matches(s, Regex.Escape(oldValue), RegexOptions.IgnoreCase))
        {
            sb.Remove(match.Index - (offset * matchNo), match.Length).Insert(match.Index - (offset * matchNo), newValue);
            matchNo++;
        }
        return sb.ToString();
    }

#12


0  

Regex.Replace(strInput, strToken.Replace("$", "[$]"), strReplaceWith, RegexOptions.IgnoreCase);

#13


0  

The regular expression method should work. However what you can also do is lower case the string from the database, lower case the %variables% you have, and then locate the positions and lengths in the lower cased string from the database. Remember, positions in a string don't change just because its lower cased.

正则表达式方法应该有效。但是,您还可以做的是降低数据库中的字符串的大小写,降低您拥有的%variable %的大小写,然后从数据库中定位小写字符串中的位置和长度。记住,字符串中的位置不会因为小写而改变。

Then using a loop that goes in reverse (its easier, if you do not you will have to keep a running count of where later points move to) remove from your non-lower cased string from the database the %variables% by their position and length and insert the replacement values.

然后使用反向的循环(如果不这样做的话,就更容易)从数据库中删除非小写字符串%variable %的位置和长度,并插入替换值。

#14


0  

(Since everyone is taking a shot at this). Here's my version (with null checks, and correct input and replacement escaping) ** Inspired from around the internet and other versions:

(因为每个人都在尝试这个)。这是我的版本(用空检查,正确的输入和替换)**来自互联网和其他版本的启发:

using System;
using System.Text.RegularExpressions;

public static class MyExtensions {
    public static string ReplaceIgnoreCase(this string search, string find, string replace) {
        return Regex.Replace(search ?? "", Regex.Escape(find ?? ""), (replace ?? "").Replace("$", "$$"), RegexOptions.IgnoreCase);          
    }
}

Usage:

用法:

var result = "This is a test".ReplaceIgnoreCase("IS", "was");