正则表达式匹配主机名-不包括TLD [英] Regex match a hostname -- not including the TLD
问题描述
我需要匹配一个主机名-但是不想要tld:
I need to match a host name--but don't want the tld:
example.com =〜/regex/=>示例
example.com =~ /regex/ => example
sub.example.com =〜/regex/=> sub.example
sub.example.com =~ /regex/ => sub.example
sub.sub.example.com =〜/regex/=> sub.sub.example
sub.sub.example.com =~ /regex/ => sub.sub.example
对正则表达式有帮助吗?谢谢.
Any help with the regex? Thanks.
推荐答案
假设您的字符串格式正确,并且不包含协议[即 http://] ,您需要所有字符,但不包括最终.tld.
Assuming your string is correctly formatted and doesn't include things like protocol [i.e. http://], you need all characters up to but not including the final .tld.
所以这是最简单的方法.正则表达式的诀窍是不要使事情变得过于复杂:
So this is the simplest way to do this. The trick with regular expressions is not to overcomplicate things:
.*(?=\.\w+)
这基本上是说,请给我集合中的所有字符,后跟[例如] .xxx ,该字符基本上只会返回上一个周期之前的所有内容
This basically says, give me all characters in the set that is followed by [for example] .xxx, which will basically just return everything prior to the last period.
如果您没有提前查找,则可能最容易使用:
If you don't have lookahead, it would probably be easiest to use:
(\w+\.)+
这将为您提供一切,包括最后一个'.'.然后只修剪'.'.
which will give you everything up to and including the final '.' and then just trim the '.'.
这篇关于正则表达式匹配主机名-不包括TLD的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!