我正在使用 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
。
关于Python:正则表达式查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30612363/