Redundant If Statement and Regex

こ雲淡風輕ζ 提交于 2021-01-29 00:17:54

问题


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)

回答1:


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)

or maybe

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.




回答2:


Save the first search and check its boolean meaning:

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


来源:https://stackoverflow.com/questions/18625778/redundant-if-statement-and-regex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!