私はAutomate boring stuff with pythonから "Regex search"プロジェクトを完了しようとしています。私は答えを探してみましたが、私は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))
P.S.私はプログラミングとスタックオーバーフローに新しいので、すべての助けに感謝しています。また、私が行動のルールを破った場合は、私に知らせてください、私は次回より良く知っているでしょう。ありがとう! – ananaa
ようこそStackOverflowコミュニティ。 '。*%s。* 'でグループ化する必要はありません* – revo
ありがとうございます!不必要な括弧が私のコードを壊すのは初めてのことではありません。 – ananaa