Python正则表达式检索两个不同分隔符之间的数字

标签 python regex

我有以下字符串

"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/

相关文章:

javascript - Html 5 模式正则表达式和最小值

python - 将 tkinter 输入与 WHERE 语句 SQLite 连接

python : NameError: global name 'GetText' is not defined

python - 检查 Python 中的文本是否被截断

c++ - 生成的getters和setters代码格式

C# 正则表达式 : print strings different from the pattern

python - 在 Python 中创建 "reversed"列表的最佳方法?

python - 在 Python 中使用 polib 修改/更新 po 文件中的条目

Python argparse 处理多个但相同的标志

regex - perl 正则表达式解释