C#:正则表达式在转换后替换匹配

时间:2017-02-12 21:46:09

标签: c# regex

现在,我正在使用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);        
}

1 个答案:

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

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