re.match
锚定在字符串的开头。这与换行符无关,所以它与使用不同^
在模式中。
As the 重新匹配文档 says:
如果零个或多个字符字符串的开头匹配正则表达式模式,返回一个
相应的MatchObject
实例。
返回None
如果字符串没有
匹配图案;请注意,这是
与零长度匹配不同。
注意:如果您想查找匹配项
字符串中的任何位置,使用search()
反而。
re.search
搜索整个字符串,如文档说:
扫描字符串寻找一个
正则表达式所在的位置
模式产生匹配,并返回
相应的MatchObject
实例。
返回None
如果没有位置
字符串与模式匹配;注意
这与寻找一个不同
中某个点的零长度匹配
细绳。
因此,如果您需要在字符串的开头匹配,或者匹配整个字符串,请使用match
。它更快。否则使用search
.
该文档有一个具体部分为match vs. search它还涵盖多行字符串:
Python提供了两种不同的原语
基于常规的操作
表达式:match
检查匹配仅在开始时字符串的,
尽管search
检查匹配anywhere在字符串中(这就是
Perl 默认情况下是这样做的)。
注意match
可能不同于search
即使使用正则表达式
以。。。开始'^'
: '^'
仅匹配
在字符串的开头,或者在MULTILINE
模式也立即
跟随换行符。这 ”match
”
操作成功仅当模式
比赛于start字符串的无论模式如何,或在开始时
位置由可选的给出pos
论点,无论是否
换行符位于其前面。
现在,说得够多了。是时候看一些示例代码了:
# 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