2017-02-12 19 views
0

現在,我正在使用Winforms(C#)的RPN計算器。例如,我可以在標籤中存儲「1/2」等分數。所以當我的標籤包含幾個分數時,我想先將它們轉換成十進制數,以便將它們放到我的堆棧中。下面你可以找到我的方法,我想怎麼做。然而,當我在我的標籤中例如「1/2」和「6/3」時,對於這兩個值,我都會得到「2」和「2」而不是「0.5」和「2」。C#:正則表達式替換後匹配

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

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);   
} 
+0

你需要做更多的'foreach'循環中。如果你只是設置分子和分母,那麼在循環之後,你只需得到兩者的最後一個值(即你的6/3 = 2)。 –

+0

我會的,謝謝! –

回答

1

這是你所需要的:

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

OR

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(); 
} 
+0

謝謝你,我會試試這個! –

+0

你好侯賽因,我不知道這是否會奏效。我的輸入字符串來自一個標籤,Form1.LabelCurrentOperation.Text,它實際上是一個非靜態屬性 –

+0

嗨,使用Form1.LabelCurrentOperation.Text = ReplaceFraction(Form1.LabelCurrentOperation.Text);你也可以刪除靜態關鍵字。 –