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"


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...