Python中的grep等价物是什么?

时间:2017-12-26 10:25:52

标签: python regex

说我有一个文字文件,其中包含'我喜欢大象'。 如果我把所说的文件和管道用于“大象大象”,我会得到整条线"我喜欢大象"。

如何在Python中使用re实现此功能? 我一直在尝试以下方法:

test = re.search('elephants', 'I like elephants.\nThey are nice')
test.group(0)

我只得到大象'而不是整个句子作为输出。

如何获得整个句子? 谢谢。

1 个答案:

答案 0 :(得分:1)

您可以使用in关键字检查您的子字符串:

with open('text_file.txt', 'r') as f:
    for line in f.readlines():
        if 'elephant' in line:
            print(line)

或者,如果您的字符串s包含\n个字符:

for line in s.split('\n'):
    if 'elephant' in line:
        print(line)

你的正则表达式只打印elephant,因为它是它捕获的内容:正是你的正则表达式字符串。如果您要尝试以下正则表达式:

test = re.search(r'(.*?elephants.*?)\n', 'I like elephants.\nThey are nice')

然后你会得到test.group(0)test.group(1)的结果,其中包括大象之前和之后的整行。

In [22]: test.group(0)
Out[22]: 'I like elephants.\n'

这是整个捕获的字符串。

In [23]: test.group(1)
Out[23]: 'I like elephants.'

这只是捕获组(括号之间的字符串)。