Regex Names which have received a B

Viewed 382

I have the folllowing lines

John SMith: A
Pedro Smith: B
Jonathan B:  A
John B: B
Luis Diaz: A
Scarlet Diaz: B

I need to get all student names which have received a B.

I tried this but it doesnt work 100%

x = re.findall(r'\b(.*?)\bB', grades)
2 Answers

You can use

\b([^:\n]*):\s*B

See the regex demo. Details:

  • \b - a word boundary
  • ([^:\n]*) - Group 1: any zero or more chars other than : and line feed
  • : - a colon
  • \s* - zero or more whitespaces
  • B - a B char.

See the Python demo:

import re
# Make sure you use 
#   with open(fpath, 'r') as f: text = f.read()
# for this to work if you read the data from a file 
text = """John SMith: A
Pedro Smith: B
Jonathan B:  A
John B: B
Luis Diaz: A
Scarlet Diaz: B"""
print( re.findall(r'\b([^:\n]*):\s*B', text) )
# => ['Pedro Smith', 'John B', 'Scarlet Diaz']

re.findall(': B') is a pretty simple way to do it, assuming there will always be exactly one space between the colon and the letter grade (which, assuming you're doing the Data Science in Python course on Coursera, there is for this assignment)

Related