问题
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