Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression accepts partial match [duplicate]

I have some validation code that checks a string against a regular expression.

Regex regex = new Regex(RegexPattern);
if (!regex.IsMatch(value))
{
    errorMessage = "The data is not in the correct format.";
    return false;
}

If I set the regular expression pattern to ^[0-9]*.[0-9]*.[0-9]*.[0-9]*$, it correctly accepts 1.0.0.0; however, it also accepts 1.0.0..

How can I modify the pattern so that 1.0.0.0 is accepted but 1.0.0. is rejected?

like image 908
Jonathan Wood Avatar asked Dec 07 '25 08:12

Jonathan Wood


2 Answers

[0-9]* means 0 or more occurrence of [0-9]

[0-9]+ means 1 or more occurrence of [0-9]

^[0-9]*.[0-9]*.[0-9]*.[0-9]*$

Change * to +:

^[0-9]+.[0-9]+.[0-9]+.[0-9]+$
like image 115
Ashkan Mobayen Khiabani Avatar answered Dec 09 '25 21:12

Ashkan Mobayen Khiabani


Just a slight misunderstanding about * and +. The former accepts either no occurrences or more (>=0), the latter only matches if such vocabulary occurs at least once (>=1).

^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$

I usually also escape the dot for safety, not entirely sure if it's necessary but I still do it. :)

like image 43
Paulo Filho Avatar answered Dec 09 '25 21:12

Paulo Filho



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!