1
我发现两种方法在Python中提取匹配:在Python中提取正则表达式匹配的正确方法是什么?
1.
def extract_matches(regexp, text):
matches = re.match(regexp, text)
if matches:
return matches.group(1)
2.
def extract_matches(regexp, text):
try:
return re.findall(regexp, text)[0]
except IndexError:
return None
哪一个你会建议我使用?你知道还有其他的方法吗?
谢谢,Boda Cydo。
语义不同。第二个发现比第一个更多。这似乎是问哪个更好'2 + 2'或者(2 + 2,3.1415928)[0]'?除了巧合之外,他们似乎没有任何相同之处。你能解释一下为什么你感到困惑吗? – 2010-03-10 16:37:35