对于下面的python代码,我正在使用正则表达式来解析字符串。但是,我正在努力从匹配的模式中提取字符串。
import re
rx = re.compile(
r'^(?P<interesting>.+?)-(?P<uid>\b\w{8}-(?:\w{4}-){3}\w{12}\b)(?P<junk>.+)$',
re.MULTILINE | re.VERBOSE)
test_str = u"00000 Gin-12-a19ea68e-64bf-4471-b4d1-44f6bd9c1708-62fa6ae2-599c-4ff1-8249-bf6411ce3be7-83930e63-2149-40f0-b6ff-0838596a9b89 Kin\n00000 Gin-a19ea68e-64bf-4471-b4d1-44f6bd9c1708 Kin\ntest123 test 12345678-1234-1234-1234-123456789012 junk afterwards\n"
tmp = re.findall(rx, test_str)
print(tmp[0])
我得到以下输出
('00000 Gin-12', 'a19ea68e-64bf-4471-b4d1-44f6bd9c1708', '-62fa6ae2-599c-4ff1-8249-bf6411ce3be7-83930e63-2149-40f0-b6ff-0838596a9b89 Kin')
我的预期输出是
00000 Gin-12
您的正则表达式中有一个命名组,因此只需使用它:
import re
rx = re.compile(r'^(?P<interesting>.+?)-(?P<uid>\b\w{8}-(?:\w{4}-){3}\w{12}\b)(?P<junk>.+)$', re.MULTILINE | re.VERBOSE)
test_str = u"00000 Gin-12-a19ea68e-64bf-4471-b4d1-44f6bd9c1708-62fa6ae2-599c-4ff1-8249-bf6411ce3be7-83930e63-2149-40f0-b6ff-0838596a9b89 Kin\n00000 Gin-a19ea68e-64bf-4471-b4d1-44f6bd9c1708 Kin\ntest123 test 12345678-1234-1234-1234-123456789012 junk afterwards\n"
tmp = re.match(rx, test_str)
print(tmp.groupdict()["interesting"])
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句