C# C替换为正则表达式多对(用于CLR SQL Server)

C# C替换为正则表达式多对(用于CLR SQL Server),c#,clr,C#,Clr,我刚刚用C为我的SQL Server实现了这个简单的CLR函数,但发现我还有另外20对需要替换,一些替换在最后完成,所以我假设它需要是正则表达式。 组织这段代码的好方法是什么,下面的一段只处理一对代码。我是C语言的新手,也许可以考虑将这些对放入数组和循环中,但可能有更好的解决方案,我可以不用循环,就像在Ruby中一样。 同时,如果速度更快的话,我也可以重复这个方块20次 Tx我看到了一些使用aka字典的方法,但出现了一些错误。如何告诉C这可能只是字符串的一部分,而不是整个字符串 select t

我刚刚用C为我的SQL Server实现了这个简单的CLR函数,但发现我还有另外20对需要替换,一些替换在最后完成,所以我假设它需要是正则表达式。 组织这段代码的好方法是什么,下面的一段只处理一对代码。我是C语言的新手,也许可以考虑将这些对放入数组和循环中,但可能有更好的解决方案,我可以不用循环,就像在Ruby中一样。 同时,如果速度更快的话,我也可以重复这个方块20次

Tx我看到了一些使用aka字典的方法,但出现了一些错误。如何告诉C这可能只是字符串的一部分,而不是整个字符串

select top 1 CLR_AddressM('alpha lane') from sys.objects
System.Collection.Generic.KeyNotFoundException:给定的密钥不存在

using System;
using System.Data.SqlTypes;
using System.Text;
using System.Text.RegularExpressions;
using Microsoft.SqlServer.Server;
using System.Collections.Generic;
using System.Linq;


namespace CLR_Functions
{
    public partial class CLRFunctions
    {    [SqlFunction( DataAccess = DataAccessKind.None, FillRowMethodName = "MyFillRowMethod"   , IsDeterministic = true)        ]

          public static string AddressM(string AddressIn)
        {
            if (string.IsNullOrEmpty(AddressIn)) return AddressIn;

              var xmlEntityReplacements = new Dictionary<string, string> {
 { "Lane$", "Ln" }, { "Avenue", "Ave" }, { "Boulevard", "Blvd" },{ "Street", "St;" }, { ".", "" }                                                                                            };

    // Create an array and populate from the dictionary keys, then convert the array 
    // to a pipe-delimited string to serve as the regex search values and replace
    return Regex.Replace(AddressIn, string.Join("|", xmlEntityReplacements.Keys.Select(k => k.ToString()).ToArray()), m => xmlEntityReplacements[m.Value]);
}    }     }

KeyNotFound异常表示您试图从字典中获取不存在的内容


在调用xmlEntityReplacements[m.Value]的地方,字典中没有m.Value——在Lane$regex的情况下,m.Value只是Lane,这就是原因

最简单的答案是在循环中遍历正则表达式,然后您仍然可以将原始密钥作为本地变量轻松访问

    public static string AddressM(string addressIn)
    {
        var xmlEntityReplacements = new Dictionary<string, string> {
         { "Lane$", "Ln" }, { "Avenue", "Ave" }, { "Boulevard", "Blvd" },{ "Street", "St;" }
            //. would match all chars ...
            , { "\\.", "" }  
        };

        foreach(var kv in xmlEntityReplacements){       
            addressIn = Regex.Replace(addressIn, kv.Key, m => xmlEntityReplacements[kv.Key],
// You might also want RegexOptions.IgnoreCase here
 RegexOptions.Compiled);

        }

        return addressIn;
    }

xmlEntityReplacements[m.Value]-发生异常是因为m.Value不是字典键,正则表达式字符串是sorry。如果您没有收到您的注释,如何修复此问题。我认为k和m是按顺序排列的。K是第一个,M是第二个TxWell,在Lane$的情况下,M的值不会相同,它只是Lane,因此在字典中找不到。此外,还有。正则表达式会处理任何输入,我想你想把它划界以匹配一个句号,比如\。谢谢Sam和所有人,我做了循环,想做些更酷的事情。谢谢你的回信。我用{@{,}解决了这个问题