Regular expression to match DNS hostname or IP Address?

后端 未结 21 2570
长发绾君心
长发绾君心 2020-11-21 07:25

Does anyone have a regular expression handy that will match any legal DNS hostname or IP address?

It\'s easy to write one that works 95% of the time, but I\'m hoping

21条回答
  •  忘掉有多难
    2020-11-21 07:50

    It's worth noting that there are libraries for most languages that do this for you, often built into the standard library. And those libraries are likely to get updated a lot more often than code that you copied off a Stack Overflow answer four years ago and forgot about. And of course they'll also generally parse the address into some usable form, rather than just giving you a match with a bunch of groups.

    For example, detecting and parsing IPv4 in (POSIX) C:

    #include 
    #include 
    
    int main(int argc, char *argv[]) {
      for (int i=1; i!=argc; ++i) {
        struct in_addr addr = {0};
        printf("%s: ", argv[i]);
        if (inet_pton(AF_INET, argv[i], &addr) != 1)
          printf("invalid\n");
        else
          printf("%u\n", addr.s_addr);
      }
      return 0;
    }
    

    Obviously, such functions won't work if you're trying to, e.g., find all valid addresses in a chat message—but even there, it may be easier to use a simple but overzealous regex to find potential matches, and then use the library to parse them.

    For example, in Python:

    >>> import ipaddress
    >>> import re
    >>> msg = "My address is 192.168.0.42; 192.168.0.420 is not an address"
    >>> for maybeip in re.findall(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}', msg):
    ...     try:
    ...         print(ipaddress.ip_address(maybeip))
    ...     except ValueError:
    ...         pass
    

提交回复
热议问题