簡體   English   中英

C#:轉換后正則表達式替換匹配項

[英]C#: Regex Replace Matches after Conversion

現在,我正在使用Winforms(C#)開發RPN計算器。 我可以在標簽中存儲“ 1/2”之類的分數。 因此,當我的標簽包含幾個分數時,我想先將它們轉換為十進制數,以便將它們放入我的堆棧中。 在下面,您可以找到我想要的方法。 但是,當我在標簽中有例如“ 1/2”和“ 6/3”時,對於這兩個值,我都將獲得“ 2”和“ 2”,而不是“ 0.5”和“ 2”。

任何想法如何解決這個問題?
提前謝謝了!

private void SearchforFrac()
{
    string pattern = @"(\d+)(/)(\d+)";
    decimal new1 = 0;
    int numerator = 0;
    int denominator = 1;

    foreach (Match match in Regex.Matches(labelCurrentOperation.Text, pattern, RegexOptions.IgnoreCase))
    {
        numerator = int.Parse(match.Groups[1].Value);
        denominator = int.Parse(match.Groups[3].Value);
    }
    new1 = (decimal)numerator / (decimal)denominator;
    String res = Convert.ToString(new1);

    Regex rgx = new Regex(pattern);
    labelCurrentOperation.Text = rgx.Replace(labelCurrentOperation.Text, res);        
}

這是您需要的:

public static string ReplaceFraction(string inputString)
{
    string pattern = @"(\d+)(/)(\d+)";
    return System.Text.RegularExpressions.Regex.Replace(inputString, pattern, (match) =>
    {
        decimal numerator = int.Parse(match.Groups[1].Value);
        decimal denominator = int.Parse(match.Groups[3].Value);
        return (numerator / denominator).ToString();
    });
}

例:

string Result = ReplaceFraction("sometext 9/3 sometext 4/2 sometext");

結果:

"sometext 3 sometext 2 sometext"

編輯

如果您無法使用上面的代碼,請嘗試以下操作:

private void SearchforFrac()
{
    string pattern = @"(\d+)(/)(\d+)";
    labelCurrentOperation.Text = System.Text.RegularExpressions.Regex.Replace(labelCurrentOperation.Text, pattern,delegate (System.Text.RegularExpressions.Match match)
    {
        decimal numerator = int.Parse(match.Groups[1].Value);
        decimal denominator = int.Parse(match.Groups[3].Value);
        return (numerator / denominator).ToString();
    });
}

要么

private void SearchforFrac()
{
    string pattern = @"(\d+)(/)(\d+)";
    this.labelCurrentOperation.Text = System.Text.RegularExpressions.Regex.Replace(this.labelCurrentOperation.Text, pattern, evaluator);
}
private string evaluator(System.Text.RegularExpressions.Match match)
{
    decimal numerator = int.Parse(match.Groups[1].Value);
    decimal denominator = int.Parse(match.Groups[3].Value);
    return (numerator / denominator).ToString();
}

暫無
暫無

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

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