Skip to main content
 首页 » 编程设计

python之如果正则表达式未找到匹配项,则返回 "Error"

2024年08月13日37bhlsheji

我有一个字符串:

link = "http://www.this_is_my_perfect_url.com/blah_blah/blah_blah?=trololo" 

我有一个函数,它从该 url 返回域名,如果找不到,则返回 '':

def get_domain(url): 
    domain_regex = re.compile("\:\/\/(.*?)\/|$") 
    return re.findall(domain_regex, str(url))[0].replace('www.', '') 
 
get_domain(link) 

返回结果:

this_is_my_perfect_url.com 

|$ 如果正则表达式不匹配则返回 ''。

有没有办法在正则表达式中实现默认值 Error,这样我就不必在函数内部做任何检查?

因此,如果 link = "there_is_no_domain_in_here",则函数返回 Error 而不是 ''。

请您参考如下方法:

如上面的评论所述,您不能在正则表达式中设置任何内容来为您执行此操作,但您可以检查 re.findall 在应用额外格式后返回的输出是否为空, 如果为空,表示没有找到匹配项,返回 Error

import re 
link = "http://www.this_is_my_perfect_url.com/blah_blah/blah_blah?=trololo" 
 
def get_domain(url): 
    domain_regex = re.compile("\:\/\/(.*?)\/|$") 
 
    #Get regex matches into a list after data massaging 
    matches = re.findall(domain_regex, str(url))[0].replace('www.', '') 
 
    #Return the match or Error if output is empty 
    return matches or 'Error' 
 
print(get_domain(link)) 
print(get_domain('there_is_no_domain_in_here')) 

输出将是

this_is_my_perfect_url.com 
Error