Regex for Host File Entries

by Captain Database on Sep 21st in Regex

Since I’m rather addicted to regex, I always end up finding ways to use them for text parsing. I randomly felt the need to make one for host file entries:

^([^#\s]*)?\s*([^#\s]+\s*)*(#.*)?$

I know it might look like it’s more complicated than it needs to be, but this expression makes the entire parsing process incredibly simple. First of all, every line in a host file will match this expression (even the blank ones). Second, the capture groups are set up in a way that will make extracting the data elements simple: group 1 is the IP, each capture in group 2 is a host name, and group 3 is the comment.

Pretty simple, but makes the process pretty elegant.

Leave a Reply

Powered By Wordpress Designed By Ridgey