开发者

C# regex to validate "realistic" IP values

Regex that somewhat validates if a value has one of the following characteristics:

123-29-123-123.subdomain.zomg.com:8085
123.12.34.56:420

Unfortunately, I'm terrible at Regex, C#, google searches, and the differen开发者_如何学编程ces between proper nouns and regular ones.

It can be a lose approximation, in fact I would go with anything that has a : colon separator with a port after it.


Will this work?

^(?<Host>[^:]+)(?::(?<Port>\d+))?$

This gives me:

Host = 123-29-123-123.subdomain.zomg.com
Port = 8085

and

Host = 123.12.34.56:420
Port = 420


Well, the simplest regex would probably be:

(\d{1,3}\.\d{1,3}\.\d{1,3})(:\d+)?

But... this would allow things like 999.999.999 which is not a valid (the format is valid, but not the values) IP address.

If you want to validate each block, best to do that outside a regex.


One can negate a match using what I call the Match Invalidator (?! ) (Match if Suffix is absent). (I wrote a blog article entited: Regular Expression (Regex) Match Invalidator (?!) in .Net on it)

In (?! Suffix) If the suffix is matched then the match fails. I have taken into account the possibilities of 256-999 and 000 using (?! ). Here is the pattern, use IgnorePatternWhiteSpace because I have commented the pattern:

string pattern = @"
^(                      # Anchor to the beginning of the line
                        # Invalidations
  (?!25[6-9])              # If 256, 257...259 are found STOP
  (?!2[6-9]\d)             # If 260-299 stop
  (?![3-9]\d\d)            # if 300-999 stop
  (?!000)                  # No zeros
  (\d{1,3})             # Between 1-3 numbers
  (?:[.-]?)             # Match but don't capture a . or -
 ){4,6}                 # IPV4 IPV6
(?<Url>[A-Za-z.\d]*?)   # Subdomain is mostly text
(?::)
(?<Port>\d+)";

HTH

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜