【问题标题】:Python String Split on pattern without removing delimiterPython字符串拆分模式而不删除分隔符
【发布时间】:2023-04-08 01:18:01
【问题描述】:

我有一根很长的绳子,每当出现某种模式时,我想把它分成更小的毒刺:(在下面的情况下为 123 my)

my_str = '123 my string is long 123 my string is very long 123 my string is so long'

我希望结果是:

result = ['123 my string is long ', '123 my string is very long ', '123 my string is so long ']

字符串长度未知。而且我不想从主字符串中删除任何内容。

【问题讨论】:

    标签: python regex split


    【解决方案1】:

    您也可以使用前瞻正则表达式:

    import re
    re.split(r'.(?=123 my)', my_str)
    =>
    ['123 my string is long',
     '123 my string is very long',
     '123 my string is so long']
    

    【讨论】:

    • 我认为这比我的努力要好,因为分隔符可以在字符串中的任何位置,例如定界符“string is”按您的预期工作。
    【解决方案2】:

    您可以在分隔符上拆分,然后使用列表理解将其重新添加:

    my_str = '123 my string is long 123 my string is very long 123 my string is so long'
    delimiter = '123 my'
    result = ['{}{}'.format(delimiter, s) for s in my_str.split(delimiter) if s]
    print(result)
    

    输出

    ['123我的弦很长','123我的弦很长','123我的弦很长']

    我不知道最后一个列表项中的尾随空格在您想要的输出中来自哪里,它不在原始字符串中,因此结果中应该不存在。

    请注意,这仅适用于分隔符从字符串开头开始的情况

    【讨论】:

      【解决方案3】:

      所以...有点笨拙,但您可以分两步完成此操作

       1. Find and replace all matches with (the match plus some custom character sequence or "\n").
      
       2. Split the new string by the custom sequence.
      

      我的做法是这样的:

      delimiter = "\n"   # or some custom pattern that won't occur in the string 
      
      def break_line(match):
         return delimiter + match.group()
      
      
      lines = re.sub(regex_pattern, break_line, text_you_want_to_split)
      lines = re.split(delimiter, lines)
      

      【讨论】:

        猜你喜欢
        • 2016-11-14
        • 2022-07-12
        • 2021-12-07
        • 2019-02-01
        • 1970-01-01
        • 2020-10-14
        • 2013-05-10
        • 1970-01-01
        相关资源
        最近更新 更多