替换正则表达式匹配项

时间:2020-06-28 19:02:28

标签: c# replace

我有这个字符串:

string coordinates = @"=ZS123, ZS1234 + 36 + Z(56)S45 + 0";

此字符串必须根据值转换为另一个字符串。正则表达式找到我需要进行计算的值。正则表达式匹配以下值:ZS123,ZS1234,Z(56)S45

Regex regexPattern1 = new Regex(@"(Z.*?S(?:\([^)]+\))?(?:\d+)?)");
string coordinates = @"=ZS123, ZS1234 + 36 + Z(56)S45 + 0";
MatchCollection matchCollection = regexPattern1.Matches(coordinates);
        
//Piece by piece the coordinates are replaced by other strings, after a calculation has been done with the matched string
foreach (Match match in matchCollection)
{
    if (match.Value.StartsWith("ZS("))
    {
        //calculations
        string cellIndex =  XY //output 
        coordinates = coordinates.Replace(match.Value, cellIndex);

        //the Match should be replaced with the calculated value(cellindex)
        //but of course this leads to a problem by doing it this way
        // my coordinates string would be now
        //coordinates = XY, XY4 + 36 + Z(56)S45 + 0";
        //it should be:
        //coordinates = XY, ZS1234 + 36 + Z(56)S45 + 0";
        //how to replace the exact match at the right spot once?
    }
    else if (match.Value.StartsWith("Z(") && match.Value.Contains("S("))
    {
        //calculations
        string cellIndex = //output 
        coordinates = coordinates.Replace(match.Value, cellIndex);
    }

   //////else if()
   //////
}

我是编程新手,非常感谢您的帮助。我希望到目前为止这是可以理解的

1 个答案:

答案 0 :(得分:1)

应该使用Regex.Replace()参数的MatchEvaluator方法的重载,而不是使用Regex.Matches(),以便可以在MatchEvaluator的方法中进行“计算”。

您的代码应如下所示:

Regex regEx = new Regex(@"(Z.*?S(?:\([^)]+\))?(?:\d+)?)");
string coordinates = @"=ZS123, ZS1234 + 36 + Z(56)S45 + 0";

string output = regEx.Replace(coordinates, delegate (Match m)
{
    string cellIndex = m.Value;
    if (m.Value.StartsWith("ZS("))
    {
        //calculations
        cellIndex = "Something";
    }
    else if (m.Value.StartsWith("Z(") && m.Value.Contains("S("))
    {
        //calculations
        cellIndex = "Something else";
    }
    // etc.

    return cellIndex;
});

请注意,我没有对您的正则表达式模式进行任何更改,因为您没有提供有关应该和不应该匹配的内容的足够信息。但是,让我指出一点...

Z.*?S部分将匹配“ Z”和“ S”之间的任意数量的字符(任何字符)。因此,它将匹配“ ZA1 @ S”之类的内容。这也是负责在您的第三次预期匹配中匹配“ Z(56)S”的部分,此处的(?:\([^)]+\))?部分与此无关。如果您的初衷是只允许在“ Z”和“ S”之间加上括号,那么您可能应该使用类似以下的内容:

Z(?:\([^)]+\))?S(?:\d+)?

另一个注意事项是,您可能希望查看自己的if条件,因为根据您的预期匹配条件,这些条件实际上并没有意义。 即,所有匹配项均不以“ ZS(”开头,或均以“ Z(”开头且包含“ S(”。)