簡體   English   中英

替換正則表達式匹配

[英]Replace Regex match

我有這個字符串:

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

我是編程新手,非常感謝您的幫助。 我希望這是迄今為止可以理解的

而不是使用Regex.Matches() ,您應該使用帶有MatchEvaluator參數的Regex.Replace()方法的重載,以便您可以在 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(”)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM