Reputation: 119
I am looking for a regex to give just the hostname
from a FQDN
.
E.g. I want just "host
" from "host.company.com
".
I've come up with this so far:
^(.{4}).*
However, because some devices stored in the CMDB dont have the full FQDN, it can also catch devices with no dot.
What I am struggling now with is when the hostname has different lengths.
Upvotes: 0
Views: 247
Reputation: 51603
^([^.]+)(\.|$| )
Should capture it (and I'm using it this way, as it provides a non-greedy regex supported by most implementations).
Upvotes: 0
Reputation: 53881
So since we are trying to get everything before the first period we do:
^(.*?)\.
The question mark indicates to match as little as possible and we escape the . to have it represent an actual dot.
Which returns "host" when matched against host.company.com.
To account for the fact that there may not be a period we use the |
modifier.
^(.*?)(\.|$)
Where $ will match the end of the line.
However if your not sure whether you need a period or not, I would say to not use a regex, instead use a find function or algorithm on the string, this will be more practical and robust.
Upvotes: 1