Dave S.
Dave S.

Reputation: 101

Simple regex failing test to determine a 3 digit number

I have had a difficult time wrapping my head around regular expressions. In the following code, I used a Regex to determine if the data passed was a 1 to 3 digit number. The expression worked if the data started with a number (ex. "200"), but also passed if the data had a letter not in the first digit (ex. "3A5"). I managed to handle the error with the INT32.TryParse() method, but it seems there should be an easier way.

    if (LSK == MainWindow.LSK6R)
    {
        int ci;
        int length = SP_Command.Length;
        if (length > 3) return MainWindow.ENTRY_OUT_OF_RANGE;   //Cannot be greater than 999

        String pattern = @"[0-9]{1,3}";               //RegEx pattern for 1 to 3 digit number
        if (Regex.IsMatch(SP_Command, pattern))       //Does not check for ^A-Z. See below.
        {
            bool test = Int32.TryParse(SP_Command, out ci);     //Trying to parse A-Z.  Only if 
            if (test)                                           //it no letter will it succeed
            {
                FlightPlan.CostIndex = ci;                      //Update the flightplan CI
                CI.Text = ci.ToString();                        //Update the Init page
            }
            else return MainWindow.FORMAT_ERROR;                //It contained a letter
        }
        else return MainWindow.FORMAT_ERROR;                    //It didn't fit the RegEx
    }

Upvotes: 1

Views: 344

Answers (2)

ntr
ntr

Reputation: 544

Adding line begin/end should help.

^[0-9]{1,3}$

Upvotes: 1

Bernhard Barker
Bernhard Barker

Reputation: 55589

Regex.IsMatch searches the input string for the pattern (and thus returns true for 3A5 because it finds 3).

You should also include start (^) and end ($) of string:

String pattern = @"^[0-9]{1,3}$";

Upvotes: 3

Related Questions