2016-09-17 80 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