我正在尝试完成"正则表达式搜索"来自书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("/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))
答案 0 :(得分:0)
在python正则表达式中,括号定义捕获组。 (有关详细说明和解释,请参阅here。)
findall
只会返回已捕获的群组。如果您想要整行,则必须迭代finditer
的结果。