代码之家  ›  专栏  ›  技术社区  ›  Bob

Python:拆分字符串并保持字符拆分

  •  0
  • Bob  · 技术社区  · 6 年前

    这是我使用regex的第一天,我遇到了一个问题。我要操纵的字符串是。。。

    1-11-1111A month and a day and a year.

    我试着分成: 1-11-1111 A month a day and a year 使用 splitstring = re.split(r'(?=\d+\d+\d+\d)', item) ,但结果是 1-11- 1111 A month a day and a year 根据我所读到的,我不确定我错在哪里。谢谢你的时间!!

    0 回复  |  直到 6 年前
        1
  •  1
  •   MDR    6 年前

    几个选项。。。

    import re
    
    pattern = re.compile(r'([0-9-]+)([A-Z].*)')
    
    item = '1-11-1111A month and a day and a year.'
    
    splitstring = [pattern.match(item)[1], pattern.match(item)[2]]
    print(splitstring)
    

    输出:

    ['1-11-1111', 'A month and a day and a year.']
    

    或者使用@Cary Swoveland的regex和原来的split(如果它是一个数字后跟大写字母“a”。。。

    splitstring = re.split(r'(?<=\d)(?=A)', item)
    splitstring
    

    输出:

    ['1-11-1111','一个月,一天,一年'.]