Posted By

qrist0ph on 05/13/08


Tagged

regExpCheatSheet cheatSheet


Versions (?)


Advertising

Website Promotion DIRECTORY is a crucial factor for all websites that need to gain better organic search engine rankings and increase website traffic.
Submitting your website as part of your Web Promotion strategy to our SEO friendly and high traffic Business Directory for review is an excellent way to gain a valuable backlink and increase your websites visibility online.

Submit Site


Who likes this?

6 people have marked this snippet as a favorite

qrist0ph
taboularasa
binarynomad
mustapha
atr000
jasonseney


Python Regular Expression Cheat Sheet


Published in: Python 






Expand | Embed | Plain Text
  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.