To do this with regex, you need to make sure that the entire quad-core quad-core IPv4 is a 32-bit leading-only number. It is not enough to make sure that each number in the square has only leading ones. For example, 255.192.255.0 is not a valid subpattern, although each number in the square has only leading numbers. Based on the solution proposed by @xanatos,
var leadingOnes = new Regex("255|254|252|248|240|224|192|128|0+");
defines a regular expression that will match any 8-bit (decimal) number with leading only. I used "0+" to use .000, which is sometimes used on quads. Obviously, if you want to force a single zero, use "0" instead.
Then you need to create a regular expression that matches any of the four following patterns that I present as pseudo regular expressions to make it easier to understand:
- 255.255.255. LeadingOnes
- 255,255. LeadingOnes *. 0
- 255. leadingOnes .0.0
- leadingOnes .0.0.0
You can either write this as a single line, or create it by concatenating. Here it is being built:
var leadingOnes = "(255|254|252|248|240|224|192|128|0+);" var allOnes = @"(255\.)"; var re = new Regex("^((" + allOnes + "{3}" + leadingOnes + ")|" + "(" + allOnes + "{2}" + leadingOnes + @"\.0+)|" + "(" + allOnes + leadingOnes + @"(\.0+){2})|" + "(" + leadingOnes + @"(\.0+){3}))$");
And here is the whole line if we ignore line breaks.
var re = new Regex(@"^(((255\.){3}(255|254|252|248|240|224|192|128|0+))|((255\.){2}(255|254|252|248|240|224|192|128|0+)\.0)|((255\.)(255|254|252|248|240|224|192|128|0+)(\.0+){2})|((255|254|252|248|240|224|192|128|0+)(\.0+){3}))$");
Following @Keith's suggestion, you can start with a simple regex like
Regex("([0-9]{1,3}\.){3}[0-9]{1,3}" to get four three-digit numbers separated by periods, and then write a function that extracts and evaluates four parts into a 32-bit integer, which you then check to make sure that it has only leadings.There are several ways to do this, but they all require up to 31 comparison operations to complete the test.
Joel lee
source share