首页 > 解决方案 > Python:拆分(子)字符串分隔符,但不是在大括号内?

问题描述

这与 Python 非常相似:通过多字符分隔符拆分字符串,除非在引号内,我从这里开始。

考虑这个测试字符串:

{{Institution Name 1} and {Institution name 2}} and {Institution name 3} and {Institution and institution name 4}

我基本上想拆分这个,所以我得到(如果包含或不包含括号,这对我来说是一样的):

  1. {Institution Name 1} and {Institution name 2}
  2. Institution name 3
  3. Institution and institution name 4

或(带括号):

  1. {{Institution Name 1} and {Institution name 2}}
  2. {Institution name 3}
  3. {Institution and institution name 4}

基本上,每组大括号分隔一个项目,项目用“ and”分隔。

但是,一个项目可以由多个项目组成,我不想在第一遍中拆分;并且“ and”也可以作为机构名称的一部分出现,在这种情况下,我也不想将其用作拆分分隔符。

从链接的帖子中修改正则表达式,我想出了and (?=(?:[^{]*{[^{]*})*[^}]*$);在https://pythex.org/链接到正则表达式)上,结果如下:

pythex-scr.png

因此,正则表达式成功地避免了“ and”作为第三项中的分隔符,它是机构名称的一部分,但它仍然用作第一个字段中的分隔符,因为它位于一组大括号内,所以应该忽略它。

有没有我可以使用的 Python 正则表达式,以给定的方式拆分?

标签: pythonregex

解决方案


您可以通过使用这样的递归正则表达式来实现这一点。

{(?>[^{}]|(?R))*}

这将导致匹配包括括号。

在这里你可以看到一个活生生的例子。


根据这个问题,regex需要模块而不是re. 然后应该支持递归。


推荐阅读