We Recommend

Learning Python Learning Python
The authors of Learning Python show you enough essentials of the Python scripting language to enable you to begin solving problems right away, then reveal more powerful aspects of the language one at a time. This approach is sure to appeal to programmers and system administrators who have urgent problems and a preference for learning by semi-guided experimentation.


Posted By

qrist0ph on 05/13/08


Tagged

regExpCheatSheet cheatSheet


Versions (?)


Who likes this?

2 people have marked this snippet as a favorite

qrist0ph
taboularasa


Python Regular Expression Cheat Sheet


Published in: Python 


  1. import re
  2.  
  3. def regexp():
  4. s = '<html><head><title>Title</title>'
  5.  
  6. # with pre compiled pattern
  7. pattern = re.compile('title')
  8. match = pattern.search(s)
  9.  
  10. #check for existence
  11. print match
  12. # >> <_sre.SRE_Match object at 0x011E0E58>
  13.  
  14. #loop through all matches
  15. match = pattern.findall(s)
  16. print match
  17. # >> ['title', 'title']
  18.  
  19. #grouping matches
  20. s = '<html><head><title>Title</title>'
  21. pattern = re.compile('(head).*(title)')
  22. match = pattern.search(s)
  23. print match.group(0)
  24. # >>head><title>Title</title
  25. print match.group(1)
  26. # >>head
  27.  
  28. #replace
  29. pattern = re.compile('title')
  30. print pattern.sub("ersetzt",s)
  31. # >> <html><head><ersetzt>Title</ersetzt>
  32.  
  33. #split
  34. pattern = re.compile('title')
  35. print pattern.split(s)
  36. # >> ['<html><head><', '>Title</', '>']
  37.  
  38. #replace alle lines in file by "eineZeile"
  39. f = open('test.txt','r')
  40. l= ['eineZeile' for l in f.readlines()]
  41. f.close()
  42. print l
  43. f=open("test.txt", "w")
  44. f.writelines(l)
  45. f.close()
  46.  
  47. regexp()

Report this snippet 

You need to login to post a comment.