re.search 与 re.match的区别

search ⇒ find something anywhere in the string and return a match object.
match ⇒ find something at the beginning of the string and return a match object.

# example code:
string_with_newlines = """something
someotherthing"""

import re

print re.match('some', string_with_newlines) # matches
print re.match('someother', 
               string_with_newlines) # won't match
print re.match('^someother', string_with_newlines, 
               re.MULTILINE) # also won't match
print re.search('someother', 
                string_with_newlines) # finds something
print re.search('^someother', string_with_newlines, 
                re.MULTILINE) # also finds something

m = re.compile('thing$', re.MULTILINE)

print m.match(string_with_newlines) # no match
print m.match(string_with_newlines, pos=4) # matches
print m.search(string_with_newlines, 
               re.MULTILINE) # also matches
posted @ 2018-08-22 18:15  bingo彬哥  阅读(498)  评论(0编辑  收藏  举报
本站总访问量