【问题标题】:Return "Error" if no match found by regex如果正则表达式找不到匹配项,则返回“错误”
【发布时间】:2019-05-29 09:37:12
【问题描述】:

我有一个字符串:

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 而不是''

【问题讨论】:

  • 不,您不能在正则表达式中设置任何内容,它只会返回在输入文本中找到的内容。您必须在代码中返回 Error
  • 正如 WiktorStribiżew 所提到的,您需要根据我在下面的回答在您的正则表达式匹配逻辑@milka1117 之外检查这一点
  • 您的意思是“返回文字字符串'错误'”而不是“引发错误/异常”?
  • 作为旁注:请考虑返回 "Error" 是否适合您的情况 - 如果您的网址是 http://www.error.com 怎么办?如果出于某种原因您不想引发错误,您可能会返回None,这在 Python 中通常用于表示 nothing
  • 是的,@Daweo 更好地表达了我试图表达的观点。将错误条件作为字符串返回不是 Pythonic。

标签: python regex


【解决方案1】:

如上面的 cmets 所述,您不能在正则表达式中设置任何内容来为您执行此操作,但您可以检查应用额外格式后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

【讨论】:

    【解决方案2】:

    只是把我的两分钱放在里面 - 懒惰的量词(.*?)与交替(|$)相结合是非常无效的。你可以vastly ameliorate your expression到:

    ://[^/]+
    

    此外,从Python 3.8 开始,您可以像在中一样使用海象运算符

    if (m := re.search("://[^/]+", your_string)) is not None:
        # found sth.
    else
        return "Error"
    

    而且不 - 使用正则表达式 单独 你无法得到某事。从一开始就不存在的字符串中。

    【讨论】:

      【解决方案3】:

      为什么不使用urlparse来获取域名?

      # env python 2
      # import urlparse
      # python 3
      from urllib.parse import urlparse
      
      
      def get_domain(url):
          parsed_uri = urlparse(url)
          domain = parsed_uri.netloc
          return domain or "ERROR"
      
      url = 'there_is_no_domain_in_here'
      print(get_domain(url))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-14
        • 1970-01-01
        • 2018-02-18
        • 1970-01-01
        • 2021-10-12
        相关资源
        最近更新 更多