使用正则表达式拆分,但保留分隔符

时间:2019-01-17 12:00:58

标签: python regex list

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

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

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

为了获得:

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

我虽然使用),作为分隔符,但是我不知道分割后如何保留)。我该怎么办?

这是我的尝试:

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

2 个答案:

答案 0 :(得分:2)

尝试此正则表达式:

(?<=\)),\s*

Click for Demo

说明:

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

然后您可以在每次比赛中执行拆分操作。

答案 1 :(得分:0)

猜猜这就是您想要的:

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

我认为您不满意是因为有人认为您没有在问题/正则表达式上付出努力。

相关问题