C # regex to check for “realistic” IP values

Regex, which checks to see if one of the following characteristics matters:

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

Unfortunately, I'm terrible in Regex, C #, Google search, and the differences between proper nouns and regular ones.

It may be a lost approximation, in fact I would go with everything that has a separator: a colon with a port after it.

+3
source share
3 answers

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-00-0020
Port = 420
+2
source

Well, the simplest regular expression will probably be:

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

... , , 999.999.999, ( , ) IP-.

, .

0

You can hide the match using what I call Invalidator Match (?!) (Match if there is no suffix ). (I wrote a blog article: Regular Expression (Regex) Match Invalidator (?!) In .Net on it)

B (?! Suffix) If the suffix matches, then the match is not performed. I took into account the possibilities of 256-999 and 000, using (?!). Here is the template, use IgnorePatternWhiteSpace because I commented on the template:

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+)";

NTN

0
source

Source: https://habr.com/ru/post/1739905/


All Articles