正则表达式从 URL 中提取子域? [英] Regex to extract subdomain from URL?
本文介绍了正则表达式从 URL 中提取子域?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一堆这样的域名:
http://subdomain.example.com(example.com 始终是 example.com,但子域因人而异).
http://subdomain.example.com (example.com is always example.com, but the subdomain varies).
我需要子域".
有耐心学习正则表达式的好心人可以帮助我吗?
Could some kind person who had the patience to learn regex help me out?
推荐答案
/(http:\/\/)?(([^.]+)\.)?domain\.com/
如果提供了子域",则 $3(或 \3)将包含子域".
Then $3 (or \3) will contain "subdomain" if one was supplied.
如果您想在第一组中拥有子域,并且您的正则表达式引擎支持非捕获组(害羞组),使用这是 palindrom 建议的:
If you want to have the subdomain in the first group, and your regex engine supports non-capturing groups (shy groups), use this as suggested by palindrom:
/(?:http:\/\/)?(?:([^.]+)\.)?domain\.com/
这篇关于正则表达式从 URL 中提取子域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文