views:

91

answers:

4

Anyone have a good (preferably tested) regex for accpeting only a valid DNS hostname, IPv4 or IPv6 address?

+2  A: 

Just go to http://www.regexlib.com/ and do a search.

serg
Yeah, the one titled "Pattern Title" is particularly good. Then again, the one called "Pattern Title" works better in some situations. Or, if you're really feeling adventurous, "Pattern Title" totally rocks! ;)
Alan Moore
+4  A: 

I understand that the may OP maybe forced to use a regex. However, if possible it is better to avoid using regexes for this task and use a Java library class to do the validation instead.

If you want to do validation and DNS lookup together, then InetAddress.getByName(String) is a good choice. This will cope with DNS, IPv4 and IPv6 in one go, and it returns you a neatly wrapped InetAddress instance that contains both the DNS name (if provided) and the IPv4 or IPv6 address.

If you just want to do a syntactic validation, then Apache commons has a couple of classes that should do the job: DomainValidator and InetAddressValidator.

Stephen C
Thanks, those Apache classes should do the trick!
Leith
+3  A: 

Guava has a new class HostSpecifier. It will even validate that the host name (if it is a host name) ends in a valid "public suffix" (e.g., ".com", ".co.uk", etc.), based on the latest mozilla public suffix list. That's something you would NOT want to attempt with a hand-crafted regex!

Kevin Bourrillion
A: 

checkout this website dude: http://regexlib.com/DisplayPatterns.aspx?cattabindex=1&categoryId=2

Saher