如何在python中使用REGR表达式打印行?

如何在python中使用REGR表达式打印行?,python,python-2.7,python-3.x,Python,Python 2.7,Python 3.x,我想使用re.search仅打印文件中所有行中的双列字符串。我只想从is打印到script 例如,file.txt包含: 我的代码: 我得到一个错误: 无类型对象没有属性组错误 我的输出应该是一行的是一个好脚本,下一行的是一个好脚本。试试这个: import re pat = re.compile(r"\bis (.*) script\b") with open("file.txt") as infile: for line in infile: print(pat

我想使用re.search仅打印文件中所有行中的双列字符串。我只想从
is
打印到
script

例如,file.txt包含:

我的代码:

我得到一个错误:

无类型对象没有属性组错误

我的输出应该是一行的
是一个好脚本
,下一行的
是一个好脚本。

试试这个:

import re

pat = re.compile(r"\bis (.*) script\b")
with open("file.txt") as infile:
    for line in infile:
        print(pat.search(line).group(1))
输出为:

a nice script language dogs are smaller than tiger perl is a good
is a nice script
is a good script
根据您问题中的新澄清进行编辑:

import re

pat = re.compile(r"\bis a \w+ script\b")
# possibly re.compile(r"\bis(.*?)script\b")
with open('file.txt') as infile:
    for line in infile:
        for match in pat.findall(line):
            print(match)
输出为:

a nice script language dogs are smaller than tiger perl is a good
is a nice script
is a good script

您使用的是python-2.7还是python-3?没有得到that@almanegra只是标记得不好。Python版本对此并不重要application@AdamSmith反问句;)我认为你不应该给他做家庭作业,但要给出失败的原因。不管怎样,回答得好+1@toasted_flakes你可能是对的。一般来说,对于那些看起来像是家庭作业问题的答案,我也会采用这种方法。诚然,我没有充分注意这一点。