python的正則表達式模塊re

1、查找文本中的模式

search()函數取模式和要掃描的文本作爲輸入,如果找到這個模式則返回一個Match對象,如果沒找到,search()將返回None

  1. #!/usr/bin/python 
  2.  
  3. import re 
  4. pattern = 'this' 
  5. text = 'Does this text match the pattern?' 
  6. match = re.search(pattern, text) 
  7. s = match.start() 
  8. e = match.end() 
  9.  
  10. print 'Found "%s"\nin "%s"\nfrom %d to %d ("%s")' % \ 
  11.         (match.re.pattern, match.string, s, e, text[s:e]) 

結果:

Found "this"
in "Does this text match the pattern?"

from 5 to 9 ("this")

2、編譯表達式

re包含一些模塊級函數,用於處理作爲文本字符串的正則表達式,不過對於程序頻繁使用的表達式,編譯這些表達式會更爲高效。compile()函數會把一個表達式字符串轉換爲一個RegexObject。
 
  1. #!/usr/bin/python 
  2.  
  3. import re 
  4. regexes = [ re.compile(p) 
  5.         for p in ['this''that'
  6.         ] 
  7. text = 'Does this text match the pattern?' 
  8. print 'Text: %r\n' % text 
  9. for regex in regexes: 
  10.     print 'Seeking "%s" ->' % regex.pattern, 
  11.     if regex.search(text): 
  12.         print 'match!' 
  13.     else
  14.         print 'no match' 
結果:
Text: 'Does this text match the pattern?'

Seeking "this" -> match!
Seeking "that" -> no match

3、多重匹配

findall()函數返回輸入中與模式匹配而不重疊的所有子串。

  1. #!/usr/bin/python 
  2.  
  3. import re 
  4.  
  5. text = 'abbaaabbbbaaaaa' 
  6. pattern = 'ab' 
  7. for match in re.findall(pattern, text): 
  8.     print 'Found "%s"' % match 
結果:
Found "ab"
Found "ab"
 
 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章