收到B的正则表达式名称
我有以下几行
John SMith: A
Pedro Smith: B
Jonathan B: A
John B: B
Luis Diaz: A
Scarlet Diaz: B
我需要获得所有获得 B 的学生姓名。
我试过这个,但它不能 100%
x = re.findall(r'b(.*?)bB', grades)
回答
您可以使用
b([^:n]*):s*B
请参阅正则表达式演示。详情:
b- 一个词边界([^:n]*)- 第 1 组:除:和换行符之外的任何零个或多个字符:- 一个冒号s*- 零个或多个空格B- 一个B字符。
请参阅Python 演示:
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']