I have a list of names and a group assigned to them as dictated by the A, B, or C letters. What I want to do is return all members of group A.
I am using a regex to find all lines that end with A, I then need to print the names of those individuals, not including the group (A, B, C)
I am running into a few issues:
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']
As you can see, I am missing Geoffrey Grupp and Simon Murphy. Additionally, I do not want to print the ": A" after each name.
You can try:
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)
It gives:
['John Doe', 'Geoffrey Grupp', 'Joseph Rose', 'Simon Murphy']
Explanation:
'(.*)'
is a capture group - the part of the pattern which will be returned; ' *'
matches possible space characters between A
and the end of the line.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.