Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex can't differentiate between float and int types

Tags:

c#

.net

regex

I have written regexes for recognizing float and int but they don't seem to work (code below).

{
    string sumstring = "12.098";

    Regex flt = new Regex(@" ^[0-9]*(\.[0-9]*)");
    Regex ent = new Regex("^[0-9]+");

    if (d_type.IsMatch(sumstring))
    {
        Console.WriteLine(sumstring + " " + "dtype");
    }

    Match m = ent.Match(sumstring);

    if (m.Success)
    {
        Console.WriteLine("int");
    }
    else if (flt.IsMatch(sumstring))
    {
        Console.WriteLine("float");
    }
}

Where is the mistake?

like image 520
intrinsic Avatar asked Feb 27 '26 19:02

intrinsic


1 Answers

First, I don't think regular expressions are really the best tool for this job. I would simply use the Double.TryParse() and Int32.TryParse() functions.

Second, you're missing a whole lot of test cases with your regular expressions:

  • Integer
    • 5 (covered)
    • +5 (not covered)
    • -5 (not covered)
  • Double
    • 5.0 (covered)
    • +5.0 (not covered)
    • -5.0 (not covered)
    • 5.0E5 (not covered)
    • 5.0E+5 (not covered)
    • 5.0E-5 (not covered)
    • +5.0E5 (not covered)
    • +5.0E+5 (not covered)
    • +5.0E-5 (not covered)
    • -5.0E5 (not covered)
    • -5.0E+5 (not covered)
    • -5.0E-5 (not covered)
  • Edge Cases
    • 2^32 + 1 (should be recognized as Double even though it looks like Integer)

All of these (except maybe the edge case) would be immediately covered by using the library instead of hand-rolling a regex.

like image 86
Lee Avatar answered Mar 01 '26 08:03

Lee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!