Following up to Regular expression to match hostname or IP Address? and using Restrictions on valid host names as a reference, what is the most readable, concise way to match/validate a hostname/fqdn (fully qualified domain name) in Python? I've answered with my attempt below, improvements welcome.
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
Process each DNS label individually by excluding invalid characters and ensuring nonzero length.
Here's a bit stricter version of Tim Pietzcker's answer with the following improvements:
[0-9]
instead of\d
).Complimentary to the @TimPietzcker answer. Underscore is valid hostname, doubel dash is common for IDN punycode. Port number should be stripped. This is the cleanup of the code.
This pure regex should meet all the parameters:
^(?=.{1,253}\.?$)(?!-)[A-Za-z0-9\-]{1,63}(\.[A-Za-z0-9\-]{1,63})*\.?(?<!-)$
If you're looking to validate the name of an existing host, the best way is to try to resolve it. You'll never write a regular expression to provide that level of validation.