我尝试使用regex从多行字符串中获取字典,但在正确分隔行方面遇到了问题。你知道吗
这是我试过的。。。你知道吗
import re
text = '''\n\n\nName: Clash1\nDistance: -1.274m\nImage Location: navis_raport_txt_files\\cd000001.jpg\nHardStatus: New\nClash Point: 1585.236m, 193.413m'''
clash_data = re.compile('''
(?P<clash_number>Clash\d+)\n
(?P<clash_depth>\d.\d{3})\n
(?P<image_location>cd\d+.jpg)\n
(?P<clash_status>\w{2:})\n
(?P<clash_point>.*)\n
(?P<clash_grid>\w+-\d+)\n
(?P<clash_date>.*)''', re.I | re.VERBOSE)
print(clash_data.search(text).groupdict())
这个类似的例子效果很好:
import re
MHP = ['''MHP-PW-K_SZ-117-R01-UZ-01 - drawing title 123''',
'MHP-PW-K_SZ-127-R01WIP - drawing title 2',
'MHP-PW-K_SZ-107-R03-UZ-1 - drawing title 3']
fields_from_name = re.compile('''
(?P<object>\w{3})[-_]
(?P<phase>\w{2})[-_]
(?P<field>\w)[-_]
(?P<type>\w{2})[-_]
(?P<dr_number>\d{3})[-_]
[-_]?
(?P<revision>\w\d{2})?
(?P<wip_status>WIP)?
[-_]?
(?P<suplement>UZ-\d+)?
[\s-]+
(?P<drawing_title>.*)
''', re.IGNORECASE | re.VERBOSE)
for name in MHP:
print(fields_from_name.search(name).groupdict())
为什么我的尝试不能像这个例子那样奏效?你知道吗
它不能工作仅仅是因为
Pattern.search()
没有找到匹配项。根据您正在模仿的工作示例,您还需要匹配输出dict中所需的命名捕获组之间的字符(以便整个模式返回匹配)。你知道吗下面是一个使用
.*\n.*
作为一种暴力方式的示例,通过匹配上一个捕获组之后的任何非换行符,然后匹配换行符,然后匹配下一个捕获组之前的任何非换行符来弥合捕获组之间的差距(您可能希望比这更精确,但它说明了这个问题)。我只包含了前3个组,因为我没有遵循您在<clash_status>
组中使用regex的意图。你知道吗相关问题 更多 >
编程相关推荐