【问题标题】:Regex split on particular length digit正则表达式拆分特定长度的数字
【发布时间】:2021-08-23 03:21:39
【问题描述】:

我有一个包含 6 位数字和超过 6 位数字的字符串。我想将它完全拆分为 6 位数字。这是我的代码。

txt = 'Hello.this.is232323dsSDdsadasd3434343'
split = re.split(r'(\d{6}?)', txt)
print(split)

但我的输出也像拆分 7 位数字一样。

['Hello.this.is', '232323', 'dsSDdsadasd', '343434', '3']

我不想仅将其他数字拆分为 6 位数字。 提前致谢。

【问题讨论】:

    标签: python-3.x regex


    【解决方案1】:

    您可以使用负后瞻和负前瞻来确保没有周围的数字。

    re.split(r"(?<!\d)(\d{6})(?!\d)", txt)
    

    输出:

    ['Hello.this.is', '232323', 'dsSDdsadasd3434343']
    

    【讨论】:

    • 啊哈!谢谢,我知道环顾四周会起作用,但无法获得正确的组合,并且没有考虑到 6 的第一个跨度可能会失败,但第二个会成功:D
    猜你喜欢
    • 1970-01-01
    • 2011-06-17
    • 2012-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-16
    • 2011-04-10
    • 1970-01-01
    相关资源
    最近更新 更多