python类中的正则表达式总是返回fal

2024-04-27 17:00:17 发布

您现在位置:Python中文网/ 问答频道 /正文

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。如果我把regex改成.*abc,那么它会输出yes。发生什么事?是不是想和整根绳子匹配?你知道吗


Tags: noselfrereturnifdefmatchfname
3条回答

the docs(我的重点):

re.match(pattern, string[, flags])

If zero or more characters at the beginning of string match the regular expression pattern, return a corresponding MatchObject instance. Return None if the string does not match the pattern; note that this is different from a zero-length match.

也许你想要.search()。你知道吗

如果要使用regex abc并使其匹配testabc,则必须使用search而不是matchmatch只匹配字符串开头;search匹配字符串中的任何位置。你知道吗

根据您添加到问题中的注释,您发现为这个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中,它处理整个字符串)

相关问题 更多 >