2010-07-27 112 views
46

可能重複:
What is the difference between Python’s re.search and re.match?蟒蛇 - re.match對re.search

我最近一直在跳進理解正則表達式與蟒蛇。

我一直在看api;我似乎無法理解的區別:對re.search

re.match的時候是最好使用每一種?利弊?利弊?

請謝謝。

+2

步驟1.搜索。 http://stackoverflow.com/questions/180986/what-is-the-difference-between-pythons-re-search-and-re-match。搜索完畢後,請提出**特定**問題。 – 2010-07-27 18:51:36

回答

53

re.match()僅匹配字符串的開頭。一個共同的問題。請參閱documentation

+2

正是。微不足道(例如沒有考慮MULTILINE模式)的實現:re.match = lambda pattern,string,flags = 0:re.search('^'+ pattern,string,flags) – delnan 2010-07-27 17:15:45

+1

@delnan:那會是'\ A'。但實際上,「匹配」比「搜索」更原始。 – kennytm 2010-07-27 17:22:19

36

search() vs. match()

re.match()檢查只在字符串的開頭匹配,而re.search()檢查匹配字符串中的任何地方。

>>> re.match("c", "abcdef") # No match 
>>> re.search("c", "abcdef") # Match 
<_sre.SRE_Match object at ...> 
7

我剛剛得知,你還可以搜索像這樣子:

if 'c' in 'abcdef' 
# True 
+2

好主意,如果你不需要它們,就避免使用正則表達式。 「有些人在遇到問題時想'我知道,我會用正則表達式'。」現在他們有兩個問題。「傑米Zawinski – neuronet 2017-08-19 19:34:16