【问题标题】:Redundant If Statement and Regex冗余 If 语句和正则表达式
【发布时间】:2013-09-05 00:10:15
【问题描述】:

以下代码显然是多余的,但根据我的经验,我经常使用这种模式。在python中有没有更好的方法来做到这一点?

if re.search("at (\d{1,2}):\d{2}", p):
    a=re.search("at (\d{1,2}):\d{2}",p).group(1)

【问题讨论】:

    标签: python regex if-statement


    【解决方案1】:

    是的,它是多余的;您应该将search() 的结果分配给一个变量,而不是调用它两次:

    m = re.search("at (\d{1,2}):\d{2}", p)
    
    if m:
        a = m.group(1)
    

    或许

    a = m.group(1) if m else some_default_value
    

    另外,如果您要经常使用此模式,请考虑使用re.compile() 预编译正则表达式。

    【讨论】:

      【解决方案2】:

      保存第一次搜索并检查其布尔含义:

      res = re.search (...)
      if res:
         a = res.group (1)
      

      【讨论】:

        猜你喜欢
        • 2020-11-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-11-28
        • 2019-12-11
        • 2011-08-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多