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

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

然而,由于某种原因,当我尝试将%PolicyAmount%替换为$0时,替换从未发生。我假设这与美元符号在正则表达式中是保留字符有关。

是否有另一种方法,我可以使用,不涉及消毒输入处理正则表达式特殊字符?


当前回答

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

然后使用一个反向循环(它更容易,如果你不这样做,你将不得不保持一个运行的计数,后来的点移动到哪里)从你的非小写字符串从数据库中删除%变量%的位置和长度,并插入替换值。

其他回答

从。net Core 2.0或。net Standard 2.1开始,这被烘焙到。net运行时[1]中:

"hello world".Replace("World", "csharp", StringComparison.CurrentCultureIgnoreCase); // "hello csharp"

[1] https://learn.microsoft.com/en-us/dotnet/api/system.string.replace#System_String_Replace_System_String_System_String_Sys tem_StringComparison_

(因为每个人都在尝试这一点)。这是我的版本(null检查,正确的输入和替换转义)**灵感来自互联网和其他版本:

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);          
    }
}

用法:

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

扩展C. Dragon 76的流行答案,将他的代码变成一个扩展,重载默认的Replace方法。

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

从MSDN $0 - "替换组号number(十进制)匹配的最后一个子字符串。"

在。net正则表达式中,0组总是整个匹配。对于字面上的$,你需要

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

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

然后使用一个反向循环(它更容易,如果你不这样做,你将不得不保持一个运行的计数,后来的点移动到哪里)从你的非小写字符串从数据库中删除%变量%的位置和长度,并插入替换值。