冗余If语句和正则表达式 [英] Redundant If Statement and Regex

查看:91
本文介绍了冗余If语句和正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码显然是多余的,但是以我的经验,我经常使用这种模式.在python中有更好的方法吗?

The following code is clearly redundant, but in my experience I use this pattern fairly often. Is there some better way to do this in python?

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

推荐答案

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

Yes, it is redundant; you should assign the result of search() to a variable instead of calling it twice:

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

此外,如果您将经常使用此模式,请考虑使用

Also, if you're going to be using this pattern frequently, consider using re.compile() to pre-compile the regex.

这篇关于冗余If语句和正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆