我有以下几行
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
参见 regex demo . 详细信息:
\b
- 单词边界([^:\n]*)
- 第 1 组:除:
和换行符之外的任何零个或多个字符:
- 冒号\s*
- 零个或多个空格B
-B
字符。
参见 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']
关于python - 收到 B 的正则表达式名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65845296/