已收到B的正则表达式名称

2024-06-10 19:07:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下几行

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)

Tags: rejohn学生姓名gradessmithbb效果
2条回答

re.findall(': B')是一种非常简单的方法,假设冒号和字母等级之间始终只有一个空格(假设您在Coursera上学习Python中的数据科学课程,则本作业有一个空格)

你可以用

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

regex demo详细信息

  • \b-单词边界
  • ([^:\n]*)-组1:除:和换行符之外的任何零个或多个字符
  • :-冒号
  • \s*-零个或多个空格
  • B-aB字符

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']

相关问题 更多 >