在锯齿状数组中使用正则表达式将第一列值替换为第二列值

Replace first column value with second column value using Regex in jagged array

在输入字符串中,我想使用下面的Jagged Array to replace the first column value with the second column prepended with \. For example, a<=bTestc<e becomes a\lebTestc\lte. How can I achieve this programatically? I'm using a Regex pattern defined below by concatenating all first column elements of the jagged array, using the | (Regex "OR") separator between each element. I've concatenated the elements by taking the elements in the order of largest length to the shortest length so that if the shorter element is contained within the larger element it does not get replaced [Ref: 。我正在使用 .NET 4.5.2

string[][] sSymb = { new string[] { "!=", "ne" }, new string[] { "lt=", "leq" }, new string[] { "<", "lt" }, new string[] { ">", "gt" }, new string[] { "<=", "le" }, new string[] { "gt=", "geq" }, new string[] { ">=", "ge" }, new string[] { "!in", "notin" }, new string[] { "sub", "subset" }, new string[] { "sup", "supset" } };
string sPattern = "gt=|!in|sub|sup|!=|<=|lt|>=|<|>";
Regex regex = new Regex(sPattern);
string st = regex.Replace("a<=bcd<e", "\$&"); //this prepends the first column element of array with \ . I need to replace the first column element with \ + second column element 
Console.WriteLine(st);

实现此目的的最简单方法是使用 overload for replace which allows you to pass in a match evaluator.

string st = regex.Replace("a<=bcd<e", match =>
{
    var matchingSymbol = sSymb.FirstOrDefault(symbol => symbol[0] == match.Value);
    if (matchingSymbol == null)
        throw new Exception("Could not find symbol to exchange.");

    return string.Concat("\",  matchingSymbol[1]);
});

此外 - 您是否必须使用锯齿状数组?使用字典会容易得多。

编辑:再次查看要匹配的键,发现顺序在这里非常重要。您需要确保要替换的条目是从最具体到最不具体的顺序排列的(否则正则表达式引擎将在本可以匹配“<=”时匹配“<”)。

在这种情况下,有序字典可能是实现此目的的最佳方式:

var sSymb = new System.Collections.Specialized.OrderedDictionary
{
    { "<=", "le" },
    { ">=", "ge" },
    { "!=", "ne" },
    { "<", "lt" },
    { ">", "gt" },
    { "gt=", "geq" }, 
    { "lt=", "leq" },
    { "!in", "notin" }, 
    { "sub", "subset" }, 
    { "sup", "supset" } 
};

var sPattern = sSymb.Keys
    .Cast<string>()
    .Aggregate((left, right) => string.Format("{0}|{1}", left, right));

Regex regex = new Regex(sPattern);
string st = regex.Replace("a<=bcd<e", match => string.Format("\{0}", sSymb[match.Value]));
Console.WriteLine(st);