class MyTest:
a = re.compile('abc')
def testthis(self, fname):
print fname
if self.a.match(fname):
return 'yes'
else:
return 'no'
如果我将'testabc'
传递给testthis()
,则会打印no
。如果我将正则表达式更改为.*abc
,则会打印出是。这是怎么回事?它是否试图匹配整个字符串?
答案 0 :(得分:4)
来自the docs(强调我的):
re.match(pattern, string[, flags])
如果字符串开头的零个或多个字符与正则表达式模式匹配,则返回相应的MatchObject实例。如果字符串与模式不匹配,则返回None;请注意,这与零长度匹配不同。
也许你想要.search()
。
答案 1 :(得分:2)
根据您添加到问题中的评论,您发现为此python代码打印的值为no
:
import re
class MyTest:
a = re.compile('abc')
def testthis(self, fname):
print fname
if self.a.match(fname):
return 'yes'
else:
return 'no'
t = MyTest()
print t.testthis('testabc')
这让你感到惊讶,因为它会在Perl中匹配。
这是因为使用Python,match
适用于字符串的开头,与Perl不同,其中m
在字符串中的任何位置查找匹配项。 (在Java中,它适用于整个字符串。)
答案 2 :(得分:1)
如果您想使用正则表达式abc
并使其与testabc
匹配,则必须使用search
而不是match
。 match
仅匹配字符串的开头; search
匹配字符串中的任何位置。