2018年4月30日 星期一

[ Python 常見問題 ] How can I find all matches to a regular expression in Python?

Source From Here 
Question 
In a program I'm writing I have Python use the re.search() function to find matches in a block of text and print the results. However, the program exits once it finds the first match in the block of text. How do I do this repeatedly where the program doesn't stop until ALL matches have been found? Is there a separate function to do this? 

How-To 
Use re.findall or re.finditer instead: 
* re.findall(pattern, string) returns a list of matching strings. 
* re.finditer(pattern, string) returns an iterator over MatchObject objects.

One simple example: 
  1. import re  
  2.   
  3. text = r'''My name is John. His name is Peter.  
  4. Today is sunny and we all want to go outside for picnic.'''  
  5.   
  6. for e in re.findall('is ([a-zA-Z]+)', text):  
  7.     print('Found "{}"'.format(e))  
Output: 
Found "John" 
Found "name" 
Found "Peter" 
Found "sunny"


沒有留言:

張貼留言

[ JS 常見問題 ] Javascript Date output formatting

Source From  Here   Question   I need to  capture the Now() date and time in the YYYY/mm/dd hh:m:sec format . It needs to be in GMT time. Ho...