1

I have an ASP.NET 4.0 MVC app in C# and I need to create a regex that will match N{3}.N{3}.N{3}.{N{3} where N{3} is any 1, 2, or 3 digits(0-9) e.g.

    1.1.1.1
    111.111.111.111
    1.111.111.1

I have tried

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

but this matches things I don't want it to like

    111.1.1
    1111.1.1

What am I doing wrong?

tereško
  • 58,060
  • 25
  • 98
  • 150
Th4t Guy
  • 1,442
  • 3
  • 16
  • 28

2 Answers2

6

A . in a regular expression means "any character." Therefore if you want to match a literal . you need to escape it, as shown below:

@"^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$"
Sean Bright
  • 118,630
  • 17
  • 138
  • 146
1

If you're trying to match an IP address, there are some great RexEx expressions here:

Regular expression to match DNS hostname or IP Address?

Community
  • 1
  • 1
Daniel Flippance
  • 7,734
  • 5
  • 42
  • 55