如何在文本文件中搜索新的行字符并打印下面的几行?

时间:2014-06-08 10:16:48

标签: python regex

我有一个文本文件,比如text.txt,它有以下信息

uncle sam
 work - xyz abc
uncle andrew
 work - xyz abc
aunt michelle 
 work - abcd wxy
aunt rosy 
 work - asdff   

问题:搜索单词'叔叔'然后使用python的正则表达式打印其相应的工作。

输出:

uncle sam
 work - xyz abc
uncle andrew
 work - xyz abc

我是python编程的新手,所以感谢任何帮助。 谢谢!

1 个答案:

答案 0 :(得分:1)

使用这个简单的正则表达式:

^uncle.*[\r\n]+.*

像这样使用:

for match in re.finditer(r"(?m)^uncle.*[\r\n]+.*", subject):
    # matched text: match.group(0)

Token-by-Token说明:

(?m)                     # ^ matches at the beginning of every line
^                        # the beginning of the string
uncle                    # 'uncle'
.*                       # any character except \n (0 or more times
                         # (matching the most amount possible))
[\r\n]+                  # any character of: '\r' (carriage return),
                         # '\n' (newline) (1 or more times (matching
                         # the most amount possible))
.*                       # any character except \n (0 or more times
                         # (matching the most amount possible))