【问题标题】:greedy regex split python every nth line贪婪的正则表达式每第n行拆分python
【发布时间】:2015-11-29 01:57:08
【问题描述】:

我的问题与one 类似,但有一些修改。首先,我需要使用 python 和正则表达式。我的字符串是:“四分和七年前。”我想每第 6 个字符分割一次,但最后如果字符不被 6 分割,我想返回空格。

我希望能够输入:'Four score and seven years ago.'

理想情况下它应该输出:['Four s', 'core a', 'nd sev', 'en yea', 'rs ago', '. ']

我能得到的最接近的是这个尝试,它忽略了我的期间并且不给我空格

re.findall('.{%s}'%6,'Four score and seven years ago.') #split into strings
['Four s', 'core a', 'nd sev', 'en yea', 'rs ago']

【问题讨论】:

    标签: python regex string


    【解决方案1】:

    不用正则表达式也很容易做到:

    >>> s = 'Four score and seven years ago.'
    >>> ss = s + 5*' '; [ss[i:i+6] for i in range(0, len(s) - 1, 6)]
    ['Four s', 'core a', 'nd sev', 'en yea', 'rs ago', '.     ']
    

    这会在您要求的末尾提供空格。

    或者,如果您必须使用正则表达式:

    >>> import re
    >>> re.findall('.{6}', ss)
    ['Four s', 'core a', 'nd sev', 'en yea', 'rs ago', '.     ']
    

    这两种情况的关键是创建字符串ss,它的末尾有足够的空格。

    【讨论】:

    • 我认为您只想添加 5 个额外的空格 (ss = s + 5*' ')。六个空格与非正则表达式示例一起工作正常;但是,对于正则表达式示例,如果您的原始字符串长度是 6 的倍数,您将获得由 6 个空格组成的最终元素。
    • @MikeCovington 非常好!谢谢。我更新了处理长度为 6 的偶数倍的字符串的答案。
    【解决方案2】:

    您没有得到包含句点的最终元素的原因是您的字符串不是 6 的倍数。因此,您需要更改正则表达式以一次匹配 1 到 6 个字符:

    >>> re.findall('.{1,6}','Four score and seven years ago.')
    ['Four s', 'core a', 'nd sev', 'en yea', 'rs ago', '.']
    

    为了获得最终元素的所需填充,只需使用以下命令:

    >>> [match.ljust(6, ' ') for match in re.findall('.{1,6}','Four score and seven years ago.')]
    ['Four s', 'core a', 'nd sev', 'en yea', 'rs ago', '.     ']
    

    【讨论】:

      【解决方案3】:

      你可以用这个:

      >>> re.findall('(.{6}|.+$)', 'Four score and seven years ago.')
      ['Four s', 'core a', 'nd sev', 'en yea', 'rs ago', '.']
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-10-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多