PawanS PawanS - 10 months ago 84
ASP.NET (C#) Question

Regular expression for subnet masking?

I am using regular expression for checking the subnet masking. I use ajax txtbox with masking value but that is not working, then I switched to a textbox and applying a regular expression for that. unfortunatly that one is also not working.

Can you help me out to give a RE for subnet masking

Or any best way to do that?


I was using masked text box and don't know how to put validation expression.

Finally I found a property of masked text box as validation expression, and there I put the RE and change the property validate to true.

No need to use validator expression explicitly.



If you want to accept any IP address as a subnet mask:

var num = @"(25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2})";
var rx = new Regex("^" + num + @"\." + num + @"\." + num + @"\." + num + "$");

I considered easier to split the "repeating" match for a single group of numbers in a separate variable.

As an exercise for the reader, I'll give another variant of the expression. This one will capture all the numbers in the same group but different captures:

var rx = new Regex("^(?:" + num + @"(?:\.(?!$)|$)){4}$");

BUT it's wrong, you should use this

var num = @"(255|254|252|248|240|224|192|128|0+)";
var rx = new Regex("^" + num + @"\." + num + @"\." +num + @"\." +num + "$");


var rx = new Regex("^(?:" + num + @"(?:\.(?!$)|$)){4}$");