美文网首页
match()与search()的区别

match()与search()的区别

作者: Geek_C | 来源:发表于2018-06-29 12:21 被阅读0次

match

如果字符串开头的零个或多个字符与正则表达式模式匹配,则返回相应的MatchObject实例。 如果字符串与模式不匹配,则返回None;

注意:如果您想在字符串中的任何位置找到匹配项,请改用search()。

search

扫描字符串查找正则表达式模式产生匹配的位置,并返回相应的MatchObject实例。 如果字符串中没有位置与模式匹配,则返回None;

# 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

相关文章

网友评论

      本文标题:match()与search()的区别

      本文链接:https://www.haomeiwen.com/subject/nefayftx.html