【问题标题】:Split using regex but keep separators使用正则表达式拆分但保留分隔符
【发布时间】:2019-01-17 12:00:58
【问题描述】:

我正在寻找 python 中正则表达式的特殊用途。我找到了一些类似的解决方案,但不知道如何使它们适应这种情况。

我想知道如何使用正则表达式拆分以下字符串:

s = '(some, word), (someword), (some other, word)'

为了获得:

['(some, word)', '(someword)', '(some other, word)']

我虽然使用), 作为分隔符,但我不知道如何在拆分后保留)。我怎么能这样做?

这是我的尝试:

re.split('\),', s)
['(some, word', ' (someword', ' (some other, word)']

【问题讨论】:

    标签: python regex list


    【解决方案1】:

    试试这个正则表达式:

    (?<=\)),\s*
    

    Click for Demo

    说明:

    • (?&lt;=\)) - 正面向后看,以确保当前位置前面有 )
    • ,\s* - 匹配 , 后跟 0+ 个空格。

    然后您可以在每次匹配时执行拆分操作。

    【讨论】:

      【解决方案2】:

      猜猜这就是你想要的:

      >>> s = '(some, word), (someword), (some other, word)'
      >>> re.findall('\(.*?\)', s)
      ['(some, word)', '(someword)', '(some other, word)']
      

      我认为你被否决是因为有人认为你没有在你的问题/正则表达式上付出努力。

      【讨论】:

        猜你喜欢
        • 2011-02-24
        • 2012-06-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-11-22
        • 1970-01-01
        • 2013-03-30
        相关资源
        最近更新 更多