简体   繁体   English

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

[英]C#: Regex Replace Matches after Conversion

Right now, I am working on a RPN calculator with Winforms (C#). 现在,我正在使用Winforms(C#)开发RPN计算器。 I am able to store fractions like "1/2" for example in a label. 我可以在标签中存储“ 1/2”之类的分数。 So when my label contains several fractions, I want to convert them first into decimal numbers, so that they will be put on my stack. 因此,当我的标签包含几个分数时,我想先将它们转换为十进制数,以便将它们放入我的堆栈中。 Below you can find my method how I want to do it. 在下面,您可以找到我想要的方法。 However, when I have for example "1/2" and "6/3" in my label, for both values I get "2" and "2" instead of "0.5" and "2". 但是,当我在标签中有例如“ 1/2”和“ 6/3”时,对于这两个值,我都将获得“ 2”和“ 2”,而不是“ 0.5”和“ 2”。

Any ideas how to solve this? 任何想法如何解决这个问题?
Many thanks in advance! 提前谢谢了!

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

This is what you need: 这是您需要的:

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

Example: 例:

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

Result: 结果:

"sometext 3 sometext 2 sometext"

EDIT 编辑

if you couldn't use code above, try this: 如果您无法使用上面的代码,请尝试以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM