Avinash
Avinash

Reputation: 3291

regular expression in .net for validating a number

I need a regular expression in .net which

Examples:

Invalid numbers:

Upvotes: 0

Views: 570

Answers (5)

Thomas
Thomas

Reputation: 2197

this regex is based on the one from Xetius:

^(100(?:\.00?)?|\d{1,2}(?:\.(?:11|10|0\d|0|1))?)$

below is the code how I Tested it:

class Program
{
    const string Pattern = @"^(100(?:\.00?)?|\d{1,2}(?:\.(?:11|10|0\d|0|1))?)$";
    static void Main(string[] args)
    {
        for (int before = 0; before < 100; before++)
        {
            Test(before.ToString());
            for (int after = 0; after < 12; after++)
            {
                Test(string.Format("{0}.{1:d2}", before, after));
                Test(string.Format("{0:d2}.{1:d2}", before, after));
                Test(string.Format(".{0:d2}", after));
            }
            Test(string.Format("{0}.{1:d}", before, 0));
            Test(string.Format("{0:d2}.{1:d}", before, 1));
        }
        // Special cases:
        Test("100");
        Test("100.0");
        Test("100.00");

        // intended to fail
        Test("00.20");
        Test("00.12");
        Test("00.00x");
        Test("000.00");
        Console.WriteLine("done.");
        Console.ReadLine();
    }

    private static void Test(string input)
    {
        Regex r = new Regex(Pattern);
        if (!r.IsMatch(input))
        {
            Console.WriteLine("no match: " + input);
        }
    }
}

Edit:

  • Tweaked the regex so that 100.0 also works
  • added a comment for the tests intended to fail

Edit2:

  • Added Test for .00 - .11 and was surprised that the regex already matched them. Thanks to Xetius

Upvotes: 1

Xetius
Xetius

Reputation: 46774

^100\.00|\d{1,2}\.(?:11|10|0\d)$

OK, was simpler than I thought.

^100(?:\.00?)?$|^(?:\d{1,2})?(?:\.(?:1|11|10|0\d?))?$

This matches the new set of data. It also matches .0 at the moment.

Upvotes: 2

Havenard
Havenard

Reputation: 27854

"^100(\.00?)?|\d\d?(\.(1[01]?|0\d?))?$"

Upvotes: 0

Lucero
Lucero

Reputation: 60190

^(?:\d{1,2}(?:\.(?:0?\d|1[01]))?|100)$

Upvotes: 0

Asaph
Asaph

Reputation: 162771

^(100(\.00?)?|\d\d?(\.(0\d|1[01]?))?)$

Upvotes: 0

Related Questions