【问题标题】:RegEx for extracting domains and subdomains用于提取域和子域的正则表达式
【发布时间】:2023-03-19 04:55:01
【问题描述】:
我正在尝试将一堆网站剥离为它们的域名,即:
https://www.facebook.org/hello
变成facebook.org。
我正在使用正则表达式模式查找器:
(https?:\/\/)?([wW]{3}\.)?([\w]*.\w*)([\/\w]*)
这可以捕获大多数情况,但偶尔会有以下网站:
http://www.xxxx.wordpress.com/hello
我想将其剥离到xxxx.wordpress.com。
如何在识别所有其他正常条目的同时识别这些案例?
【问题讨论】:
标签:
python
regex
regex-lookarounds
regex-group
regex-greedy
【解决方案1】:
您的表达式似乎工作得非常好,它会输出您可能想要的内容。我只添加了一个i 标志并稍微修改为:
(https?:\/\/)?([w]{3}\.)?(\w*.\w*)([\/\w]*)
正则表达式
如果这不是您想要的表达式,您可以在regex101.com 中修改/更改您的表达式。
正则表达式电路
您还可以在jex.im 中可视化您的表达式:
Python 代码
# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility
import re
regex = r"(https?:\/\/)?([w]{3}\.)?(\w*.\w*)([\/\w]*)"
test_str = ("https://www.facebook.org/hello\n"
"http://www.xxxx.wordpress.com/hello\n"
"http://www.xxxx.yyy.zzz.wordpress.com/hello")
subst = "\\3"
# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 0, re.MULTILINE | re.IGNORECASE)
if result:
print (result)
# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.
JavaScript 演示
const regex = /(https?:\/\/)?([w]{3}\.)?(\w*.\w*)([\/\w]*)/gmi;
const str = `https://www.facebook.org/hello
http://www.xxxx.wordpress.com/hello
http://www.xxxx.yyy.zzz.wordpress.com/hello`;
const subst = `$3`;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log('Substitution result: ', result);
【解决方案2】:
虽然 Robert Harvey 提出了一个有用的方法 urllib.parse,但这是我对正则表达式的尝试:
(?:http[s]?:\/\/)?(?:www\.)?([^/\n\r\s]+\.[^/\n\r\s]+)(?:/)?(\w+)?
如regex101.com所见
解释-
首先,正则表达式检查是否存在https:// 或http://。如果是这样,它会忽略它,但之后会开始搜索。
然后正则表达式检查www. - 重要的是要注意这是可选的,所以如果用户输入my website is site.com,site.com 将被匹配。
[^/\n\r\s]+\.[^/\n\r\s]+ 匹配您需要的实际 url,因此它不会有空格或换行符。哦,其中必须至少有一个句点 (.)。
由于您的问题看起来您也想匹配子目录,所以我在末尾添加了(\w+)?。
TL;DR
第 0 组 - 整个网址
第 1 组 - 域名
第 2 组 - 子目录
【解决方案3】:
print("-------------")
# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility
import re
regex = r"(https?:\/\/)?([w]{3}\.)?(\w*.\w*)([\/\w]*)"
regex1 = r"\.?(microsoft.com.*)"
test_str = (
"https://blog.microsoft.com/test.html\n"
"https://www.blog.microsoft.com/test/test\n"
"https://microsoft.com\n"
"http://www.blog.xyz.abc.microsoft.com/test/test\n"
"https://www.microsoft.com")
subst = "\\3"
if test_str:
print (test_str)
print ("-----")
# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 0, re.MULTILINE | re.IGNORECASE)
if result:
print (result)
print ("-----")
result = re.sub(regex1, "", result, 0, re.MULTILINE | re.IGNORECASE)
if result:
print (result)
print ("-----")