映射函数和正则表达式?
Map functions and regex?
我正在尝试从 URL 的列表中获取域。为此,我在函数中使用正则表达式进行模式匹配。
def get_domain(url):
m = re.search(r"https:\/\/(.*)\/", url)
result = m.group(1)
return result;
string_array = ("hTTps://stack0verflow.com/", "hTTps://stackoverfl0w.com/", "hTTps://stackoverfiow.com/")
m = list(map(get_domain, string_array))
如果我使用 for 循环遍历字符串列表,函数 get_domain 可以工作,但每当我尝试使用 map 函数时,我都会收到以下错误。
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-23-575cbcab950e> in <module>
9 print(get_domain(url))
10
---> 11 m = list(map(get_domain, string_array))
12 ##print(m)
<ipython-input-19-fc11e511d74d> in get_domain(url)
12 def get_domain(url):
13 m = re.search(r"https:\/\/(.*)\/", url)
---> 14 result = m.group(1)
15 return result;
AttributeError: 'NoneType' object has no attribute 'group'
为什么会这样,我做错了什么?我在网上看到了很多 map 函数的例子,我想我已经掌握了语法。
此正则表达式将仅获得第一组中的域名:
(?:https?:\/\/)?(?:(?:www|ssh).)?((?=.*\.)[^\n\/]*)
并且不要忘记使其不区分大小写
例子:
import re
arr = ["https://www.exemple.com/?query=blablabla","https://www.exemple.com/aaa","hTTp://www.exemple.com","www.exemple.com/aaa","exemple.com"]
for i in arr:
m = re.search(r"(?:https?:\/\/)?(?:(?:www|ssh).)?((?=.*\.)[^\n\/]*)",i,re.IGNORECASE)
print(m.group(1))
我正在尝试从 URL 的列表中获取域。为此,我在函数中使用正则表达式进行模式匹配。
def get_domain(url):
m = re.search(r"https:\/\/(.*)\/", url)
result = m.group(1)
return result;
string_array = ("hTTps://stack0verflow.com/", "hTTps://stackoverfl0w.com/", "hTTps://stackoverfiow.com/")
m = list(map(get_domain, string_array))
如果我使用 for 循环遍历字符串列表,函数 get_domain 可以工作,但每当我尝试使用 map 函数时,我都会收到以下错误。
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-23-575cbcab950e> in <module>
9 print(get_domain(url))
10
---> 11 m = list(map(get_domain, string_array))
12 ##print(m)
<ipython-input-19-fc11e511d74d> in get_domain(url)
12 def get_domain(url):
13 m = re.search(r"https:\/\/(.*)\/", url)
---> 14 result = m.group(1)
15 return result;
AttributeError: 'NoneType' object has no attribute 'group'
为什么会这样,我做错了什么?我在网上看到了很多 map 函数的例子,我想我已经掌握了语法。
此正则表达式将仅获得第一组中的域名:
(?:https?:\/\/)?(?:(?:www|ssh).)?((?=.*\.)[^\n\/]*)
并且不要忘记使其不区分大小写
例子:
import re
arr = ["https://www.exemple.com/?query=blablabla","https://www.exemple.com/aaa","hTTp://www.exemple.com","www.exemple.com/aaa","exemple.com"]
for i in arr:
m = re.search(r"(?:https?:\/\/)?(?:(?:www|ssh).)?((?=.*\.)[^\n\/]*)",i,re.IGNORECASE)
print(m.group(1))