Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
78 views
in Technique[技术] by (71.8m points)

python - Regex Names which have received a B

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', grades)
question from:https://stackoverflow.com/questions/65845296/regex-names-which-have-received-a-b

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use

([^:
]*):s*B

See the regex demo. Details:

  • - a word boundary
  • ([^: ]*) - 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'([^:
]*):s*B', text) )
# => ['Pedro Smith', 'John B', 'Scarlet Diaz']

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...