【问题标题】:split string using regex every 6 digits每 6 位使用正则表达式拆分字符串
【发布时间】:2022-01-01 20:22:02
【问题描述】:

我基本上需要在接下来的6位数字和冒号之前分割一个字符串:

import re
my_str = '610640: 168 hours 610835: till next day 14:00 617041:  168 hours 611486:720 hours'
match = re.split(r'(\d{6}\:)', my_str)
print(match)
for item in match:
    print(item)

阅读610640: 168 hours610835: till next day 14:00617041: 168 hours等等。我尝试过的其他正则表达式:

(\d{6}\:)+.*?(\d{6}\:)

我一直在使用https://pythex.org/ 来了解如何编写正则表达式

【问题讨论】:

    标签: python-3.x regex


    【解决方案1】:

    有了匹配项,您就快到了,但是您应该将最后一部分转为前瞻而不是匹配项,并使用交替断言字符串的结尾来获取最后一项。

    在这部分(\d{6}\:)+ 中,您可以省略组和重复,因为它只出现 1 次,冒号不必转义。

     \b\d{6}:.*?(?=\s*(?:\d{6}:|$))
    

    查看regex demo

    如果你想使用 re.split,你也可以使用:

    (?<!^)\b(?=\d{6}:)
    

    查看regex demo

    import re
    my_str = '610640: 168 hours 610835: till next day 14:00 617041:  168 hours 611486:720 hours'
    match = re.split(r'(?<!^)\b(?=\d{6}:)', my_str)
    print(match)
    for item in match:
        print(item.strip())
    

    输出

    ['610640: 168 hours ', '610835: till next day 14:00 ', '617041:  168 hours ', '611486:720 hours']
    610640: 168 hours
    610835: till next day 14:00
    617041:  168 hours
    611486:720 hours
    

    如果总是有 1 个或多个前导空白字符,您可以匹配它们以拆分并省略单词边界:

    match = re.split(r'\s+(?=\d{6}:)', my_str)
    

    查看Python demo

    【讨论】:

    • 谢谢 :) 我将检查您附加到正则表达式的每个选项,将在 10m 内接受答案。它的工作 100% :)
    • 确实\s+(?=\d{6}:)应该够好了
    猜你喜欢
    • 2017-02-23
    相关资源
    最近更新 更多