Regex verify IP

2

I am implementing a regex to accept IP address, for this I am using a mask in the textEdit component of DevExpress, but when I leave the field blank or with only a filled part it locks all other controls of the form.

Regex used:

([0-9]{1,3}\.){3}[0-9]{1,3} 
    
asked by anonymous 01.02.2017 / 12:55

3 answers

4

Solution

/^((1?\d{1,2}|2([0-4]\d|5[0-5]))\.){3}(1?\d{1,2}|2([0-4]\d|5[0-5]))$|^$/

Explanation

  • Note that you want to validate IP so you can not just use \d{1,3} because you would be accepting 999 .
  • (1?\d{1,2}|2([0-4]\d|5[0-5])) this REGEX will validate numbers from 0 to 255.
  • ((1?\d{1,2}|2([0-4]\d|5[0-5]))\.){3} add of the literal point and must be repeated 3 times
  • ^$ would be "nothing", in case it starts and ends.

Be working at REGEX101 .

    
02.02.2017 / 12:11
2

An alternative is to use your own method, such as this, to validate IP in the form of IPv4:

public bool ValidateIPv4(string ipString)
{
    if (String.IsNullOrWhiteSpace(ipString))
    {
        return false;
    }

    string[] splitValues = ipString.Split('.');

    if (splitValues.Length != 4)
    {
        return false;
    }

    byte tempForParsing;

    return splitValues.All(r => byte.TryParse(r, out tempForParsing));
}

Implementation:

string ip1 = "q.1;00.1.";       
string ip2 = "127.0.0.1";
string ip3 = "999.0.0.2";

Console.WriteLine(ValidateIPv4(ip1));
Console.WriteLine(ValidateIPv4(ip2));
Console.WriteLine(ValidateIPv4(ip3));

Output:

  

False
  True
  False

This method is an alternative to IPAdress.Tryparse that you own limitations and may return incorrect results. It is also easy to maintain since it has only three rules to determine if the IP address is valid.

Font .

    
03.02.2017 / 00:13
0

Try to use this regex:

^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$

At first it will validate each line of your TextEdit, starting with the first letter, if you want to validate anywhere in the text, remove ^ from the beginning.

    
01.02.2017 / 13:06