0

I want to use regular expression to check whether a given string is an IP address or not. My first idea was ^([0-2][0-9]{1,2}|[0-9]{1,2})\.\1\.\1\.\1$, but then I remembered that backreferences are referencing to the result of the capturing group. So my solution would work for IP adresses like 192.192.192.192, 168.168.168.168 or 178.178.178.178. Is there another type of backreference that references to the regex of a capturing group instead of referencing to a result of the capturing group? Is there a better way than using ([0-2][0-9]{1,2}|[0-9]{1,2})\. four times in a row? Or does the .NET Framework offer functions to check strings whether they are IPs or not?

Cubi73
  • 1,891
  • 3
  • 31
  • 52
  • You could say that my question is a duplicate, but I think I ask some more things, didn't I? – Cubi73 Jul 11 '14 at 19:55

1 Answers1

1

You can use

IPAddress.TryParse

EZI
  • 15,209
  • 2
  • 27
  • 33
  • Sounds logically, but this functions sees strings like `192` or `192.168` as IPs and returns true for them. – Cubi73 Jul 11 '14 at 20:10
  • @Cubinator73 Read the comments in the answer linked. You can also combine above method with, for ex, `192.168.1.1".Count(x => x == '.') == 3;` – EZI Jul 11 '14 at 20:25