【问题标题】:Regular expression to get a string between two strings in Python在Python中获取两个字符串之间的字符串的正则表达式
【发布时间】:2021-04-09 09:09:35
【问题描述】:

您能否建议如何提取{0之间的字符串}以及{字符串开头并从右侧被0覆盖}和{字符串在末尾并从左侧被0覆盖}

'1001130001' -> [1,113,1]
'0001130001' -> [113,1]
'0001130000' -> [113]

编辑:我还需要知道每个字符串的位置。 (匹配对象)

【问题讨论】:

    标签: python python-3.x regex


    【解决方案1】:

    我认为即使没有正则表达式:

    txts = ['1001130001', '0001130001', '0001130000']
    for s in txts:
        print(list(map(int, filter(None, s.split('0')))))
    

    如果您必须使用正则表达式,请尝试:

    import re
    txts = ['1001130001', '0001130001', '0001130000']
    for s in txts:
        print(list(map(int, re.findall(r'[1-9]+', s))))
    

    两个选项都返回:

    [1, 113, 1]
    [113, 1]
    [113]
    

    编辑:

    既然你提到你还需要匹配对象的位置,你可以使用re.finditer 和一些列表理解:

    import re
    txts = ['1001130001', '0001130001', '0001130000']
    for s in txts:
        print([[m.start(), int(m.group())] for m in re.finditer(r'[1-9]+', s)])
    

    打印:

    [[0, 1], [3, 113], [9, 1]]
    [[3, 113], [9, 1]]
    [[3, 113]]
    

    【讨论】:

      【解决方案2】:

      看起来您只想按零序列分割。

      >>> import re
      >>> re.split('0+', '1001130001')
      ['1', '113', '1']
      

      为了不产生空结果,您可以使用str.strip 预处理您的字符串。

      >>> re.split('0+', '0001130000')
      ['', '113', '']
      >>> re.split('0+', '0001130000'.strip('0'))
      ['113']
      

      【讨论】:

        【解决方案3】:

        我更喜欢re.findall这里:

        inp = ["1001130001", "0001130001", "0001130000"]
        for val in inp:
            matches = re.findall(r'(?<![^0])[^\D0]+(?![^0])', val)
            print(matches)
        

        打印出来:

        ['1', '113', '1']
        ['113', '1']
        ['113']
        

        下面是正则表达式模式的解释:

        (?<![^0])  assert that what precedes is either zero OR the start of the input
        [^\D0]+    match one or more digit characters other than zero
        (?![^0])   assert that what follows is either zero OR the end of the input
        

        【讨论】:

        • 你得到了我的投票,但这不是写[1-9]+的一种非常复杂的方式吗? =)
        • @JvdV ... 除非 OP 的实际输入类似于 1abc0001230abc3,即它只希望非零数字夹在零之间(而不是其他字符)。这或许可以解释为什么我的回答比你的更受欢迎。
        猜你喜欢
        • 2014-12-08
        • 2011-08-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多