[Python] re.search() vs re.match()
Contents
為什麼要比這兩個呢?因為我就是誤用的受害者O_____Q
而且官方文件特別開一個 section 來比,可見很多人誤用吧(笑
官方文件是這樣寫的:
Python offers two different primitive operations based on regular expressions: re.match() checks for a match only at the beginning of the string, while re.search() checks for a match anywhere in the string.
簡單來說,兩個funciton用法大同小異,都是去找string裡面符合pattern的字串,但還是有一些小差別。
match()
從字串的頭開始找,只要字串開頭不符合 pattern,就不會回傳任何東西,會是一個 NoneType
。
在這個例子裡,要找的 pattern 是 ‘name’,但 ‘name’ 卻不在 test 的開頭,所以會 match 不到東西。
search()
可以在字串裡任意的位置尋找你要的 pattern。
同樣的 pattern,用 search()
的結果就不一樣了,可以順利找到要找的 pattern ‘name’。
今天為了這個我弄了快一個小時了吧!!!!!
得到教訓,下次要學乖了。