2013-11-27 47 views
6

我有一個包含的Python re.search

string = "123hello456world789" 

串不包含spacess字符串變量。我想要寫一個正則表達式,使得僅打印含有(A-Z) 話我嘗試了簡單的regex

pat = "([a-z]+){1,}" 
match = re.search(r""+pat,word,re.DEBUG) 

匹配對象包含唯一字Hello和字World不匹配。

何時使用re.findall()我可以同時得到HelloWorld

我的問題是爲什麼我們不能用re.search()做到這一點?

這是怎麼回事re.search()

+0

因爲'hello'和'world'不相鄰,但這就是你的模式所尋找的。 –

+1

你爲什麼想用're.search'來做這件事? –

+0

在我的原始正則表達式中,我有大約4個組。通過,使用** re.findall **與組,我無法獲得完整的匹配。而使用** re.search()**,我可以使用** match.group()完成匹配** –

回答

9

re.search()發現圖案一旦字符串中,documenation

掃描通過串尋找其中定期 表達模式產生一個匹配的位置,並返回對應的 MatchObject實例。如果字符串中沒有位置匹配 模式,則返回無;請注意,這與在字符串中的某處找到零長度的 匹配不同。

爲了匹配發生,你需要re.findall()documentation

返回所有非重疊的字符串模式的匹配,作爲 字符串列表。字符串從左到右掃描,匹配返回 找到的順序。如果該模式中存在一個或多個組,則 會返回組列表;如果模式 有多個組,這將是元組列表。空結果包含在結果 中,除非它們觸及另一場比賽的開始。

例子:

>>> import re 
>>> regex = re.compile(r'([a-z]+)', re.I) 
>>> # using search we only get the first item. 
>>> regex.search("123hello456world789").groups() 
('hello',) 
>>> # using findall we get every item. 
>>> regex.findall("123hello456world789") 
['hello', 'world'] 

UPDATE:

由於your duplicate questionas discussed at this link)我在這裏加了我其他的答案,以及:

>>> import re 
>>> regex = re.compile(r'([a-z][a-z-\']+[a-z])') 
>>> regex.findall("HELLO W-O-R-L-D") # this has uppercase 
[] # there are no results here, because the string is uppercase 
>>> regex.findall("HELLO W-O-R-L-D".lower()) # lets lowercase 
['hello', 'w-o-r-l-d'] # now we have results 
>>> regex.findall("123hello456world789") 
['hello', 'world'] 

正如您所看到的,您提供的第一個示例失敗的原因是由於大寫,因此您可以簡單地添加re.IGNORECASE標誌,儘管您提到匹配應僅爲小寫。

+1

由於某些原因,OP不想使用'findall()'。這是問題的全部。 –

+0

@MartijnPieters OP也問:「爲什麼我們不能用re.search()做到這一點」 –

+0

你最初的編輯沒有回答這個問題。 –

1

@InbarRose答案顯示爲什麼重新。搜索的工作原理是這樣的,但如果你想match對象,而不是僅僅從re.findall字符串輸出,使用re.finditer

>>> for match in re.finditer(pat, string): 
...  print match.groups() 
... 
('hello',) 
('world',) 
>>> 

或者相反,如果你想要一個list

>>> list(re.finditer(pat, string)) 
[<_sre.SRE_Match object at 0x022DB320>, <_sre.SRE_Match object at 0x022DB660>] 

這也是一般一個壞主意假設它是一個通用模塊,請使用string作爲變量名稱。