python - 收到 B 的正则表达式名称

标签 python regex

我有以下几行

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/

相关文章:

python - 提取 Pandas 中日期时间类型列的第一天

python - 类函数变量

Python从某个元素开始重新排列列表

java - 如何正确转义该字符串?

python - 在 Python 中合并两个表

python - 配置 Passenger_wsgi.py 以使用 Pelican

mysql - 如何在 MySQL 中搜索没有定义字符的字符串?

Python 字符串列表和正则表达式列表,找到不匹配的字符串的干净方法?

c++ - 生成的getters和setters代码格式

javascript - 如何在javascript中使用正则表达式检索div中的内容