Python:子类别的正则表达式查找?

标签 python regex

正在关注 this question ,我正在考虑在字符串中包含一个层次结构。例如这是我的字符串:

sometext
somemore    text here

some  other text

              course: course1

some details
TestName: test1
some other details
Id              Name                marks
____________________________________________________
1               student1            65
2               student2            75
3               MyName              69
4               student4            43

some details
TestName: test3
some other details
Id              Name                marks
____________________________________________________
1               student1            23
3               MyName              63
4               student4            64


              course: course2

some details
TestName: test2
some other details
Id              Name                marks
____________________________________________________
1               student1            84
2               student3            73

some details
TestName: test5
some other details
Id              Name                marks
____________________________________________________
1               MyName              84
2               student2            73


              course: course4

some details
TestName: test1
some other details
Id              Name                marks
____________________________________________________
1               student1            58
2               student3            89

some details
TestName: test2
some other details
Id              Name                marks
____________________________________________________
1               student1            97
3               MyName              60
8               student6            82

我想获取 MyName 的详细信息。类似 (course1,test1,69),(course1,test3,63),(course2,test5,84),(course4,test2,60) 或类似输出的输出。

我无法一步完成,因此想到了这个:

import re
eachcourse = re.split(r'course: \w+',string1)
courselist = re.findall(r'course: (\w+)',string1)
li =[]
for i,course in enumerate(courselist):
    match = re.findall(r".*?TestName: (\w+)(?:(?!\TestName\b).)*MyName\s+(\d+).*?",eachcourse[i+1],re.DOTALL)
    li.append((course,match))
print li

这给了我

[('course1', [('test1', '69'), ('test3', '63')]), ('course2', [('test5', '84')]), ('course4', [('test2', '60')])]

有没有更好更简洁的方法?

谢谢。

最佳答案

x=re.findall(r"\bcourse: (\w+)(.*?)(?=(?:\bcourse:|$))",x,flags=re.DOTALL)


print [[i[0]]+re.findall(r"TestName: (\w+)(?:(?!\bTestName\b).)*MyName\s*(\d+)",i[1],flags=re.DOTALL) for i in x]

你可以试试这个,虽然格式不完全一样,但是可以用。

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

相关文章:

python - 如何为我的数据集创建类似直方图的条形图?

python - 试图将项目附加到 python 中的列表,但它的行为很奇怪

Python 参数解析 : nargs + or * depending on prior argument

python - 检查python类属性

c++ - 使用 C++ 在 Evil Hangman 游戏中存储和处理词族

ios - 从字符串创建 Twitter 句柄数组

objective-c - 电子邮件地址的正则表达式

python - 如何使用 Pandas 在时间序列中查找连续的相同数据

JavaScript 正则表达式 : validate time

regex - 导入名称不同月份的文件