Regex check IP

Asked

Viewed 1,157 times

3

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

Regex used:

([0-9]{1,3}\.){3}[0-9]{1,3} 
  • ([0-9]{1,3}\.){3}[0-9]{1,3} -- protect the .

  • Victorfreitas, what are empty characters? And you want empty characters in the IP?

  • Sorry Joao, the right thing would be to accept the empty field, in case the user gives up filling the field.

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 cannot simply use \d{1,3}, because you’d 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} addendum of the literal point and must be repeated 3 times
  • the ^$ would be the "nothing", in the case begins and already ends.

Whether working on REGEX101.

2

An alternative is to use a method of its own, 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));

Exit:

False
True
False

This method is an alternative to Ipadress.Tryparse. which has 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.

Source.

0

Try using that 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 from the first letter, if you want to validate any part of the text, remove the beginning.

  • This regex is with some problems, besides not accepting the empty field, it keeps showing the characters of at the beginning of the string and the $ character at the end of the string.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.