用正则表达式查找多行?
问题描述:
我正在尝试从Automate boring stuff with python书中完成“正则表达式搜索”项目。我试图寻找答案,但我未能在python中找到相关的线程。用正则表达式查找多行?
任务是:“编写一个程序,打开文件夹中的所有.txt文件,并搜索与用户提供的正则表达式匹配的任何行,结果应打印在屏幕上。
随着下面编译我设法找到的第一个匹配
regex = re.compile(r".*(%s).*" % search_str)
而且我可以
print(regex.search(content).group())
打印出来,但如果我尝试使用
print(regex.findall(content))
的输出只是输入的单词/单词,而不是他们所在的整个行。为什么findall
不符合整行,即使这是我编译正则表达式的方式?
我的代码如下。
# Regex search - Find user given text from a .txt file
# and prints the line it is on
import re
# user input
print("\nThis program searches for lines with your string in them\n")
search_str = input("Please write the string you are searching for: \n")
print("")
# file input
file = open("https://*.com/users/viliheikkila/documents/kooditreeni/input_file.txt")
content = file.read()
file.close()
# create regex
regex = re.compile(r".*(%s).*" % search_str)
# print out the lines with match
if regex.search(content) is None:
print("No matches was found.")
else:
print(regex.findall(content))
P.S.我是新手编程和*,所以所有的帮助表示赞赏。另外,如果我违反了任何行为准则,请告诉我,下次我会更好地了解。谢谢! – ananaa
欢迎来到*社区。你根本不需要分组''。*%s。*' – revo
谢谢队友!这不是第一次不必要的括号毁了我的代码。 – ananaa