MT.S
MT.S

Reputation: 25

C#: Regex Replace Matches after Conversion

Right now, I am working on a RPN calculator with Winforms (C#). I am able to store fractions like "1/2" for example in a label. 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".

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

Upvotes: 0

Views: 144

Answers (1)

Hossein Golshani
Hossein Golshani

Reputation: 1897

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

Upvotes: 1

Related Questions