正则表达式匹配主机名——不包括 TLD
我需要匹配主机名 - 但不需要 tld:
example.com =~ /regex/ => 示例
sub.example.com =~ /regex/ => sub.example
sub.sub.example.com =~ /regex/ => sub.sub.example
对正则表达式有帮助吗? 谢谢。
I need to match a host name--but don't want the tld:
example.com =~ /regex/ => example
sub.example.com =~ /regex/ => sub.example
sub.sub.example.com =~ /regex/ => sub.sub.example
Any help with the regex? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
尝试这个
在不支持 ?= 的情况下
,然后获取第一组的内容
Try this
without support of the ?= it would be
and then take the content of the first group
你可以去掉 tld:
You could just strip off the tld:
这并不是真正特定于顶级域名,它只会为您提供一行中最后一个句点之前的所有内容。 如果您想对有效 TLD 或其他任何内容严格要求,则必须以不同的方式编写。
This isn't really specific to tlds, it'll just give you everything before the last period in a line. If you want to be strict about valid TLDs or anything, it'll have to be written differently.
我不清楚你想如何让比赛顺利进行。 但使用通常的扩展正则表达式,您应该能够将任何 tld 与
[a-zA-Z]{2,3}
匹配,因此,如果您试图获取除 tld 之外的整个名称,类似的东西应该很接近。
I'm not clear how you want to make the match work. but with the usual extended regex, you should be able to match any tld with
[a-zA-Z]{2,3}
So if you're trying to get the whole name other than the tld, something likeshould be close.
假设您的字符串格式正确并且不包含诸如协议之类的内容 [ie http://],您需要最多的所有字符但不包括最终的 .tld。
所以这是最简单的方法。 正则表达式的技巧不是让事情变得过于复杂:
这基本上是说,给我后面跟着的集合中的所有字符[例如] .xxx,这基本上将只需返回最后一个时期之前的所有内容即可。
如果您没有前瞻功能,它可能是最容易使用的:
它将为您提供直到并包括最后的“.”的所有内容。 然后只需修剪“.”即可。
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:
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:
which will give you everything up to and including the final '.' and then just trim the '.'.