2016-09-17 119 views
1

我正在尝试从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://stackoverflow.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)) 
+0

P.S.我是新手编程和stackoverflow,所以所有的帮助表示赞赏。另外,如果我违反了任何行为准则,请告诉我,下次我会更好地了解。谢谢! – ananaa

+0

欢迎来到StackOverflow社区。你根本不需要分组''。*%s。*' – revo

+0

谢谢队友!这不是第一次不必要的括号毁了我的代码。 – ananaa

回答

0

在蟒的正则表达式,括号限定捕获组。 (请参见here的细节和说明)。

findall将只返回捕获的组。如果你想要整行,你将不得不遍历finditer的结果。

+0

谢谢!这非常有帮助。实际上我通过删除括号来运行代码。并感谢一个很好的链接。 – ananaa