我有一个文本文件,比如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编程的新手,所以感谢任何帮助。 谢谢!
答案 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))