Python - 递归查找项目的正则表达式

Python - Regex to find items recursively

首先,我想在文件中找到所有包含字符串 'xyz' 的行 - 我使用

来执行此操作

示例文件:

This is about me. 
My name is xyz and I live in USA. 
There is also a restaurant called xyz in my city.
The food at the xyz is yummy check out their menu. 
The restaurant is 5 miles from my home.

with open('file1.txt', 'r') as file1:
    pattern = re.compile('xyz', re.IGNORECASE)
    for line in file1:
        if pattern.search(line):
            print(line)

所以输出是:

My name is xyz and I live in USA. 
There is also a restaurant called xyz in my city.
The food at the xyz is yummy check out their menu.

此外,我还需要在输出行中匹配单词 'restaurant'“仅当它存在时”,并在同一文件中找到包含该 'restaurant' 的所有行。所以最终输出应该是

My name is xyz and I live in USA. 
There is also a restaurant called xyz in my city.
The food at the xyz is yummy check out their menu. 
The restaurant is 5 miles from my home.

如果我们将您的示例文本写成段落,即。一行由于自动换行而成为多行,但不包含回车 return 或行尾,那么我们可以同时捕获 2 个单词,如下所示 如果它们始终处于相同的顺序 .

^.*xyz.*restaurant.*$

如果它们可以按任何顺序排列,我们需要使用 2 个正向预测。

^(?=.*xyz)(?=.*restaurant).*$