Python:正则表达式查找

标签 python regex

我正在使用 python 正则表达式从给定字符串中提取某些值。这是我的字符串:

我的字符串.txt

sometext
somemore    text here

some  other text

              course: course1
Id              Name                marks
____________________________________________________
1               student1            65
2               student2            75
3               MyName              69
4               student4            43

              course: course2
Id              Name                marks
____________________________________________________
1               student1            84
2               student2            73
8               student7            99
4               student4            32

              course: course4
Id              Name                marks
____________________________________________________
1               student1            97
3               MyName              60
8               student6            82

我需要提取特定学生的类(class)名称和相应分数。例如,我需要上述字符串中 MyName 的类(class)和分数。

我试过:

re.findall(".*?course: (\w+).*?MyName\s+(\d+).*?",buff,re.DOTALL)

但这仅在每门类(class)下都存在 MyName 时有效,但如果某些类(class)中缺少 MyName 则无效,例如在我的示例字符串中。

这里我得到的输出是:[('course1', '69'), ('course2', '60')]

但实际上我想要实现的是:[('course1', '69'), ('course4', '60')]

正确的正则表达式是什么?

#!/usr/bin/python    
import re

buffer_fp = open("mystring.txt","r+")
buff = buffer_fp.read()
buffer_fp.close()
print re.findall(".*?course: (\w+).*?MyName\s+(\d+).*?",buff,re.DOTALL)

最佳答案

.*?course: (\w+)(?:(?!\bcourse\b).)*MyName\s+(\d+).*?

                    ^^^^^^^^^^^^

您可以试试这个。请参阅演示。只需使用基于前瞻的量词,它将在 类(class) 之前搜索 MyName

https://regex101.com/r/pG1kU1/26

关于Python:正则表达式查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30612363/

相关文章:

javascript - js 正则表达式匹配以 X 开头而不是 Y 开头的路径

python - "Pair words Extractor"- 正则表达式

python - Scipy 和 Sklearn chi2 实现给出不同的结果

python - 使用 "subprocess.call()"时真实有效用户发生变化

python:如何转义路径中的斜线?

python - 如何将变音符号与正则表达式匹配?

c# - 在 C# 中使用正则表达式格式化字符串

python - Windows 10 上的 opencv python 相机权限问题

python - 无法使用 PySpark xgboost4j 保存模型

Java 正则表达式(无空格或 0-9)