代码之家  ›  专栏  ›  技术社区  ›  user2064000

在字符上拆分字符串,转义时除外

  •  1
  • user2064000  · 技术社区  · 8 年前

    我有几个字符串,我想在空格和字符上拆分 " ,则, ' ,则, ( ,则, ) ,则, ; ,则, | & ,除非他们带着 \

    以下是一些示例:

    "hello-world" -> [r"hello-world"]
    "hello;world " -> [r"hello", r"world"]
    "he(llo)(w|o rld)" -> ["he", "llo", "w, "o", "rld"]
    r"hello\;world" -> [r"hello\;world"]
    r"hello\-world" -> [r"hello\-world"]
    

    为此,我编写了regex:

    r'''(?:[^\s"'();|&]+|\\.)+'''
    

    它适用于所有其他情况,但以下情况除外:

    >>> re.findall(r'''(?:[^\s"'();|&]+|\\.)+''', r'hello\;world')
    ['hello\\', 'world']
    

    如何修改regex以获得预期的结果?

    我宁愿不使用 re.split() ;上面的正则表达式是一个更大的正则表达式的一部分,用于使用 .findall()

    1 回复  |  直到 8 年前
        1
  •  2
  •   Wiktor Stribiżew    8 年前

    你的 [^\s"'();|&]+ 图案部分抓住 \ 然后 \\. 无法正确匹配转义字符。

    您可以使用

    (?:\\.|[^\s"'();|&\\])+
    

    请参见 regex demo

    这里,模式匹配任何转义字符的1个或多个重复(如果使用 re.DOTALL re.S ,甚至包括换行符),或除空格以外的任何字符, " ,则, ' ,则, ( ,则, ) ,则, ; ,则, | ,则, & \

    Python demo :

    import re
    strs = ['hello-world', r'hello;world ', r'he(llo)(w|o rld)', r'hello\;world',r'hello\-world ']
    for s in strs:
        res = re.findall(r'''(?:\\.|[^\s"'();|&\\])+''', s)
        for val in res:
            print(val)
        print("-------------")
    

    输出:

    hello-world
    -------------
    hello
    world
    -------------
    he
    llo
    w
    o
    rld
    -------------
    hello\;world
    -------------
    hello\-world
    -------------