[英]Python Regex - How to account for end-of-line and end-of-file AND print only subsection of string?
我有一個由 A、B 或 C 字母指示的名稱列表和分配給它們的組。 我想要做的是返回 A 組的所有成員。
我正在使用正則表達式查找以 A 結尾的所有行,然后我需要打印這些人的姓名,不包括組(A、B、C)
我遇到了幾個問題:
import re
test_str = ("John Doe: A\n"
"Jane Washington: B\n"
"Geoffrey Grupp: A \n"
"Joseph Rose: A\n"
"Victoria Georges: C \n"
"Simon Murphy: A")
regex = r"^.*[A]$\n"
result= re.findall(regex, test_str, re.MULTILINE)
result
Out[8]: ['John Doe: A\n', 'Joseph Rose: A\n']
如您所見,我想念 Geoffrey Grupp 和 Simon Murphy。 此外,我不想在每個名稱后打印“:A”。
你可以試試:
import re
test_str = ("John Doe: A\n"
"Jane Washington: B\n"
"Geoffrey Grupp: A \n"
"Joseph Rose: A\n"
"Victoria Georges: C \n"
"Simon Murphy: A")
regex = r"^(.*): A *$"
result= re.findall(regex, test_str, re.MULTILINE)
print(result)
它給:
['John Doe', 'Geoffrey Grupp', 'Joseph Rose', 'Simon Murphy']
解釋:
'(.*)'
是一個捕獲組 - 將返回的模式部分;' *'
匹配A
和行尾之間可能存在的空格字符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.