我有以下字符串
"h=56,7,1,d=88,9,1,h=58,8,1,d=45,h=100,d=,"
我想使用正则表达式来提取组:
- 组1 56,7,1
- 组2 88,9,1
- 组3 58,8,1
- 组4 45
- 第5组100
- 组6为空
我的最终目标是拥有诸如(group1,group2),(group3,group4),(group5,group6)之类的元组。我不确定这一切是否可以用正则表达式来完成。
我有以下正则表达式,给出了部分结果
(?<=h=|d=)(.*?)(?=h=|d=)
匹配项末尾有一个额外的逗号,如 56,7,1,
,我想将其删除,并且 d=,
不会返回 null。
最佳答案
您可能不需要使用正则表达式。一个list comprehension和 .split()
可能可以做你需要的事情,例如:
代码:
def split_it(a_string):
if not a_string.endswith(','):
a_string += ','
return [x.split(',')[:-1] for x in a_string.split('=') if len(x)][1:]
测试代码:
tests = (
"h=56,7,1,d=88,9,1,h=58,8,1,d=45,h=100,d=,",
"h=56,7,1,d=88,9,1,d=,h=58,8,1,d=45,h=100",
)
for test in tests:
print(split_it(test))
结果:
[['56', '7', '1'], ['88', '9', '1'], ['58', '8', '1'], ['45'], ['100'], ['']]
[['56', '7', '1'], ['88', '9', '1'], [''], ['58', '8', '1'], ['45'], ['100']]
关于Python正则表达式检索两个不同分隔符之间的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48898617/