简体   繁体   中英

Python Regex - How to account for end-of-line and end-of-file AND print only subsection of string?

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:

  1. The very last entry is in group A, however this is not the end of a line but end of file and is being ignored.
  2. Some records contain a space before the end of line indicator and are being passed over.
  3. I only want to print the name and not the group.

Code

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

Output

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM