code_junkie

What is the difference between Python's re.search and re.match?

Nov 11th, 2011
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.72 KB | None | 0 0
  1. # example code:
  2. string_with_newlines = """something
  3. someotherthing"""
  4.  
  5. import re
  6.  
  7. print re.match('some', string_with_newlines) # matches
  8. print re.match('someother',
  9. string_with_newlines) # won't match
  10. print re.match('^someother', string_with_newlines,
  11. re.MULTILINE) # also won't match
  12. print re.search('someother',
  13. string_with_newlines) # finds something
  14. print re.search('^someother', string_with_newlines,
  15. re.MULTILINE) # also finds something
  16.  
  17. m = re.compile('thing$', re.MULTILINE)
  18.  
  19. print m.match(string_with_newlines) # no match
  20. print m.match(string_with_newlines, pos=4) # matches
  21. print m.search(string_with_newlines,
  22. re.MULTILINE) # also matches
Add Comment
Please, Sign In to add comment