3

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?

Ashkan Mobayen Khiabani
  • 33,575
  • 33
  • 102
  • 171
Jonathan Wood
  • 65,341
  • 71
  • 269
  • 466

4 Answers4

5

[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]+$
Ashkan Mobayen Khiabani
  • 33,575
  • 33
  • 102
  • 171
2

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. :)

Paulo Filho
  • 343
  • 2
  • 13
0

You can use this pattern:

^\d+\.\d+\.\d+\.\d+$

Explanation:

 ^ - begin of string
   \d - any digit
   + - at least one char
   \. - exactly a dot char
 $ - end of string

By the way, your input looks like an IP address. If so you can modify your reges like this:

^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$

{1,3} means: 'from 1 to 3 chars'

Demo: regex101

Aleks Andreev
  • 7,016
  • 8
  • 29
  • 37
0

To match 4 sets of digits separated by a period

^\d+(?:\.\d+){3}$