【问题标题】:python: split string without discarding anythingpython:拆分字符串而不丢弃任何内容
【发布时间】:2017-02-23 15:59:55
【问题描述】:

我想做这样的事情:

import re
s = 'This is a test'
re.split('(?<= )', s)

添加返回类似这样的内容:

['This ', 'is ', 'a ', 'test']

但这不起作用。

谁能建议一种简单的方法来根据正则表达式拆分字符串(我的实际代码更复杂,并且确实需要正则表达式)而不丢弃任何内容?

【问题讨论】:

  • 类似[i for i in re.split('([^ ]+ ?)',s) if i]?
  • @fredtantini 您应该将其添加为答案
  • @fredtantini 太棒了!我曾经说过 Perl 是 21 世纪的 APL...
  • @fredtantini 将正则表达式放在括号中似乎会改变 re.split 的行为。这在某处有记录吗?
  • @BrentBaccala 引用 docs.python.org/2/library/re.html#re.split If capturing parentheses are used in pattern, then the text of all groups in the pattern are also returned as part of the resulting list

标签: python regex string split


【解决方案1】:

re.split() 的目的是定义一个分隔符来分割。虽然您会找到其他可以让您的案例真正发挥作用的答案,但我觉得您会更喜欢 re.findall()

之类的东西
re.findall(r'(\S+\s*)', s)

给你

['This ', 'is ', 'a ', 'test']

【讨论】:

    【解决方案2】:

    您可以在这里使用regex 模块。

    import regex
    s = 'This is a test'
    print regex.split('(?<= )', s,flags=regex.VERSION1)
    

    输出:

    ['This ', 'is ', 'a ', 'test']

    import re
    s = 'This is a test'
    print [i for i in re.split(r'(\w+\s+)', s,) if i]
    

    注意:0 width assertions are not supported in re module for split

    【讨论】:

      【解决方案3】:

      为什么不直接使用re.findall

      re.findall(r"(\w+\s*)", s)
      

      【讨论】:

        【解决方案4】:

        捕获分隔符,然后将分隔符重新连接到前一个单词:

        >>> it = iter(re.split('( )', s)+[''])
        >>> [word+delimiter for word, delimiter in zip(it, it)]
        ['This ', 'is ', 'a ', 'test']
        

        【讨论】:

          【解决方案5】:

          至少字母字符和一个空格用于拆分:

          [i for i in re.split('(\w+ +)',s) if i] # ['This ', 'is ', 'a ', 'test']
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2021-07-06
            • 2022-01-20
            • 1970-01-01
            • 2017-04-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-01-03
            相关资源
            最近更新 更多