python - 如果未包含分隔符,则将字符串拆分为列表

标签 python regex

我正在开发一个简单的维基引擎,我想知道是否有一种有效的方法可以根据分隔符将字符串拆分为列表,但前提是该分隔符没有用双方括号或双花括号括起来括号。

所以,像这样的字符串:

"|Row 1|[[link|text]]|{{img|altText}}|"

将转换为如下列表:

['Row 1', '[[link|text]]', '{{img|altText}}']

编辑:从示例字符串中删除了空格,因为它们会引起困惑。

最佳答案

你可以使用

def split_special(subject):
    return re.split(r"""
        \|           # Match |
        (?!          # only if it's not possible to match...
         (?:         # the following non-capturing group:
          (?!\[\[)   # that doesn't contain two square brackets
          .          # but may otherwise contain any character
         )*          # any number of times,
         \]\]        # followed by ]]
        )            # End of first loohahead. Now the same thing for braces:
        (?!(?:(?!\{\{).)*\}\})""", 
        subject, flags=re.VERBOSE)

结果:

>>> s = "|Row 1|[[link|text|df[sdfl|kj]|foo]]|{{img|altText|{|}|bar}}|"
>>> split_special(s)
['', 'Row 1', '[[link|text|df[sdfl|kj]|foo]]', '{{img|altText|{|}|bar}}', '']

请注意前导和尾随空字符串 - 它们需要存在,因为它们确实存在于测试字符串中的第一个 | 之前和最后一个 | 之后。

关于python - 如果未包含分隔符,则将字符串拆分为列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19202749/

相关文章:

python - 如何在Python中获取图像的对象轮廓(外边界)?

python - 从 python 中的导入语句中查找

php - 如何确定一个字符串是否是 PHP 中的数学语句?

python - 使用 Regex 和 BeautifulSoup 解析 Python 中的字符串

regex - 如何在 MongoDB 中拆分字符串?

python - 编辑 Pandas 脚本以忽略但不删除数据然后匹配和更新+比较以防止浪费保存+切片数据以匹配?

python - 在 python 语法错误中使用 ffmpeg 调整大小

python : Get items of one attribute (by value) in Json files

python - 如何将列表列表除以 Python 中的另一个列表列表?

c++ - QString 的替代品是什么?