Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't this C# regular expression working?

Tags:

c#

regex

c#-4.0

I tried to write an expression to validate the following pattern:

digit[0-9] at 1 time exactly
"dot"
digit[0-9] 1-2 times
"dot"
digit[0-9] 1-3 times
"dot"
digit[0-9] 1-3 times or “hyphen”

For example these are legal numbers:

1.10.23.5
1.10.23.-

these aren't:

10.10.23.5
1.254.25.3

I used RegexBuddy to write the next pattern:

[0-9]\.[0-9]{1,2}\.[0-9]{1,3}\.[0-9]{1,3}|[0-9]\.[0-9]{1,2}\.[0-9]{1,3}\.-

In RegexBuddy all seems perfect but in my code I am getting true about illegal numbers (like 10.1.1.1)

I wrote the next method for validating this pattern:

 public static bool IsVaildEc(string ec)
        {
            try
            {
                if (String.IsNullOrEmpty(ec))
                    return false;
                string pattern = @"[0-9]\.[0-9]{1,2}\.[0-9]{1,3}\.[0-9]{1,3}|[0-9]\.[0-9]{1,2}\.[0-9]{1,3}\.-";
                Regex check = new Regex(pattern);
                return check.IsMatch(ec);
            }
            catch (Exception ex)
            {
                //logger
            }
        }

What am I doing wrong?

like image 295
Ofir Avatar asked Jan 14 '23 07:01

Ofir


1 Answers

You regex isn't anchored to the start and end of the string, therefore it also matches a substring (e. g. 0.1.1.1 in the string 10.1.1.1).

As you can see, RegexBuddy matches a substring in the first "illegal" number. It correctly fails to match the second number because the three digits in the second octet can't be matched at all:

RegexBuddy Screenshot

string pattern = @"^(?:[0-9]\.[0-9]{1,2}\.[0-9]{1,3}\.[0-9]{1,3}|[0-9]\.[0-9]{1,2}\.[0-9]{1,3}\.-)$";

will fix that problem.

Then, your regex is needlessly complicated. The following does the same but simpler:

string pattern = @"^[0-9]\.[0-9]{1,2}\.[0-9]{1,3}\.(?:[0-9]{1,3}|-)$";
like image 176
Tim Pietzcker Avatar answered Jan 25 '23 15:01

Tim Pietzcker