Regex for IP address

后端 未结 6 1260
失恋的感觉
失恋的感觉 2020-11-28 14:59

I tried this code for validating IP address, but it doesn\'t work...

public static bool IP(string ipStr)
{
    string pattern = @\"^([1-9]|[1-9][0-9]|1[0-9][         


        
相关标签:
6条回答
  • 2020-11-28 15:07

    There is a previously answered question available for a valid IP address.

    As for debugging regular expressions, on Windows I heartily recommend Expresso. On the web, there is a free Flash-based tester available.

    0 讨论(0)
  • 2020-11-28 15:07

    For CIDR format in both ipv4 and ipv6

    http://blog.markhatton.co.uk/2011/03/15/regular-expressions-for-ip-addresses-cidr-ranges-and-hostnames/

    0 讨论(0)
  • 2020-11-28 15:18

    I'm not really a regex expert per se but i use Expresso (a regex tool) and it has it's own regex library for pre-set scenarios like this. Try this below.

    string pattern = @"(?<First>2[0-4]\d|25[0-5]|[01]?\d\d?)\.(?<Second>2[0-4]\d|25[0-5]|[01]?\d\d?)\.(?<Third>2[0-4]\d|25[0-5]|[01]?\d\d?)\.(?<Fourth>2[0-4]\d|25[0-5]|[01]?\d\d?)";
    
    0 讨论(0)
  • 2020-11-28 15:23

    Here is the complete regex for checking all possible IPv4 addresses (dotted decimal, dotted hexadecimal, dotted octal, decimal, hexadecimal, octal and mixed mode)

    ^(0[0-7]{10,11}|0(x|X)[0-9a-fA-F]{8}|(\b4\d{8}[0-5]\b|\b[1-3]?\d{8}\d?\b)|((2[0-5][0-5]|1\d{2}|[1-9]\d?)|(0(x|X)[0-9a-fA-F]{2})|(0[0-7]{3}))(\.((2[0-5][0-5]|1\d{2}|\d\d?)|(0(x|X)[0-9a-fA-F]{2})|(0[0-7]{3}))){3})$
    

    I have tested it with all possible addresses.

    0 讨论(0)
  • 2020-11-28 15:28

    I would use IPAddress.TryParse static method instead.

    IPAddress ip;
    bool b = IPAddress.TryParse("1234.12.12.12",out ip);
    
    0 讨论(0)
  • 2020-11-28 15:28

    for match a valid IP adress use

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

    instead of

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

    because many regex engine match the first possibility in the OR sequence

    you can try your regex engine : 10.48.0.200

    test the difference here

    0 讨论(0)
提交回复
热议问题