【问题标题】:Split at multiple delimiter without delimiter in the list在列表中没有分隔符的多个分隔符处拆分
【发布时间】:2013-06-07 15:04:15
【问题描述】:

这应该是使用re 库的一项非常简单的任务。但是,我似乎无法在分隔符 ][ 处拆分我的字符串。

我已经阅读了Splitting a string with multiple delimiters in PythonPython: Split string with multiple delimitersPython: How to get multiple elements inside square brackets

我的字符串:

data = "This is a string spanning over multiple lines.
        At somepoint there will be square brackets.

        [like this]

        And then maybe some more text.

        [And another text in square brackets]"

它应该返回:

['This is a string spanning over multiple lines.\nAt somepoint there will be square brackets.','like this', 'And then maybe some more text.', 'And another text in square brackets']

一个简短的例子:

data2 = 'A new string. [with brackets] another line [and a bracket]'

我试过了:

re.split(r'(\[|\])', data2)
re.split(r'([|])', data2)

但是那些会导致在我的结果列表中包含分隔符或完全错误的列表:

['A new string. ', '[', 'with brackets', ']', ' another line ', '[', 'and a bracket', ']', '']

结果应该是:

['A new string.', 'with brackets', 'another line', 'and a bracket']

作为一项特殊要求,应删除分隔符前后的所有换行符和空格,也不应包含在列表中。

【问题讨论】:

    标签: python regex split


    【解决方案1】:

    正如 arshajii 指出的那样,对于这个特定的正则表达式,您根本不需要组。

    如果您确实需要组来表达更复杂的正则表达式,您可以使用非捕获组来拆分而不捕获分隔符。它在其他情况下可能有用,但在这里语法混乱过度。

    (?:...)

    A non-capturing version of regular parentheses. Matches whatever regular expression is inside the parentheses, but the substring matched by the group cannot be retrieved after performing a match or referenced later in the pattern.
    

    http://docs.python.org/2/library/re.html

    因此,这里不必要的复杂但具有示范性的示例是:

    re.split(r'(?:\[|\])', data2)
    

    【讨论】:

      【解决方案2】:

      改用这个(没有捕获组):

      re.split(r'\s*\[|]\s*', data)
      

      或更短:

      re.split(r'\s*[][]\s*', data)
      

      【讨论】:

        【解决方案3】:

        可以拆分或全部查找,例如:

        data2 = 'A new string. [with brackets] another line [and a bracket]'
        

        使用拆分和过滤前导/尾随空格:

        import re
        print filter(None, re.split(r'\s*[\[\]]\s*', data2))
        # ['A new string.', 'with brackets', 'another line', 'and a bracket']
        

        或者可能,采用 findall 方法:

        print re.findall(r'[^\b\[\]]+', data2)
        # ['A new string. ', 'with brackets', ' another line ', 'and a bracket'] # needs a little work on leading/trailing stuff...
        

        【讨论】:

          【解决方案4】:
          >>> re.split(r'\[|\]', data2)
          ['A new string. ', 'with brackets', ' another line ', 'and a bracket', '']
          

          【讨论】:

          • 是的,这比我推荐的非捕获组更简单。
          • 效果很好。作为补充:如何删除元素末尾/开头的所有换行符和空格?
          • 好的。弄清楚了。对列表中的每个元素使用strip()。再次感谢。
          • @cherrun re.split(r'\s*[\[\]]\s*', data2)怎么样?
          猜你喜欢
          • 2019-05-11
          • 1970-01-01
          • 2021-05-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-01-18
          • 1970-01-01
          相关资源
          最近更新 更多