None 在 python 的正则表达式中找到

None found into a regex with python

我正在尝试查找以 #number 开头的表达式 在 Python 中使用正则表达式进入文件 3. 文件类似于:

#123= toto(ikpm,guio,gyio)
#126= tutu(kop,cfyg,jipo)
#246= toto(gyui,rtf,kjoip)
...

和python代码:

LineRe = re.compile('^#([0-9]+)= .+$')
with open(path,'r') as f:
    for line in f:
        if "toto" in line:
            lre = LineRe.fullmatch(line)
            print(lre)
            if not lre is None:
                number = lre.group(1)
                print(lre)
                print(number)

我的正则表达式 ^#([0-9]+)= .+$Test RegEx 似乎没问题,但我的代码总是打印 'None'... 请问有什么问题吗?

我不知道 fullmatch() 所以当我尝试 search()match() 时,效果很好

LineRe = re.compile('^#([0-9]+)= .+$')
with open(path,'r') as f:
    for line in f:
        if "toto" in line:
            lre = LineRe.search(line)
            print(lre)
            if not lre is None:
                number = lre.group(1)
                print(lre)
                print(number)

您也可以使用match()

重新导入

LineRe = re.compile('#([0-9]+)= .+')
with open(path,'r') as f:
    for line in f:
        if "toto" in line:
            lre = LineRe.match(line)
            print(lre)
            if not lre is None:
                number = lre.group(1)
                print(lre)
                print(number)

输出::

<_sre.SRE_Match object; span=(0, 26), match='#123= toto(ikpm,guio,gyio)'>
<_sre.SRE_Match object; span=(0, 26), match='#123= toto(ikpm,guio,gyio)'>
123
<_sre.SRE_Match object; span=(0, 26), match='#246= toto(gyui,rtf,kjoip)'>
<_sre.SRE_Match object; span=(0, 26), match='#246= toto(gyui,rtf,kjoip)'>
246

来自@Eamonn Kenny 的回答:

You just forgot to rstrip() your line before running fullmatch() on it. The hint of this is in the comment of seer.The. He/She said that it worked fine for them, so they are obviously using only one line of text or a windows machine.

lre = LineRe.fullmatch(line.rstrip())

你只是忘了在 运行 完全匹配之前重新删除你的行。 seer.The 的评论中有提示。 He/She 说这对他们来说效果很好,所以他们显然只使用一行文本或一台 windows 机器。

lre = LineRe.fullmatch(line.rstrip())

您的代码在其他方面都很完美。