RegEx for an IP Address

前端 未结 12 1565
不知归路
不知归路 2020-11-29 03:52

I try to extract the value (IP Address) of the wan_ip with this sourcecode: Whats wrong?! I´m sure that the RegEx pattern is correct.

String input = @\"var p         


        
12条回答
  •  清歌不尽
    2020-11-29 04:32

    Avoid using /b - it allows characters before or after the IP
    For example ...198.192.168.12... was valid.

    Use ^ and $ instead if you can split the input into chunks that would isolate the IP address.

         Regex regexIP = new Regex(@"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$");
    
         if (regexIP.Match(textBoxIP.Text).Success){
             String myIP = textBoxIP.Text;
         }
    

    Note above will not validate the digits, as pointed out 172.316.254.1 was true. This only checks correct formatting.


    UPDATE: To validate FORMATTING and VALUES you could use

         Regex regexIP = new Regex(@"^([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])\.([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])$");
    
         if (regexIP.Match(textBoxIP.Text).Success){
             String myIP = textBoxIP.Text;
         }
    

    (note using ([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5]) for each numeric value)
    Credit: https://stackoverflow.com/a/10682785/4480932

提交回复
热议问题