簡體   English   中英

如何僅替換匹配集合中的特定匹配?

[英]How do I replace only specific match in a match collection?

我正在編寫一個求解方程的求解方法。 該方法將是遞歸的; 搜索所有外括號,找到時召回解決括號內的值,並在沒有找到括號時返回值。

過程應該是這樣的

20 * (6+3) / ((4+6)*9)
20 * 9 / ((4+6)*9)
20 * 9 / (10*9)
20 * 9 / 90
2

如您所見,每個匹配項可能具有不同的替換值。 我需要將括號替換為它的評估結果。 有沒有辦法做到這一點。 這是我到目前為止所擁有的。

public int solve(string etq)
{
    Regex rgx = new Regex(@"\(([^()]|(?R))*\)");
    MatchCollection matches;

    matches = rgx.Matches(etq);
        
    foreach(Match m in matches)
    {
        //replace m in etq with unique value here
    }

    //calculations here
    return calculation
}

Regex.replace(...) 替換所有出現的指定模式。 我希望能夠匹配多個場景並用不同的輸出替換每個場景

簡單的解決方案:

string input = "20 * (6+3) / ((4+6)*9)";
Console.WriteLine(input);
DataTable dt = new DataTable();
Regex rx = new Regex(@"\([^()]*\)");
string expression = input;
while (rx.IsMatch(expression))
{
    expression = rx.Replace(expression, m => dt.Compute(m.Value, null).ToString(), 1);
    Console.WriteLine(expression);
}
Console.WriteLine(dt.Compute(expression, null));

https://dotnetfiddle.net/U6Hh1e

這將是一個更簡單的解決方案,使用匹配屬性來替換使用子字符串:

public static string Replace(this Match match, string source, string replacement) { return source.Substring(0, match.Index) + replacement + source.Substring(match.Index + match.Length); }

暫無
暫無

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

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