除非转义,否则在字符上拆分字符串

时间:2018-05-14 14:23:47

标签: python regex python-3.x

我有几个字符串,我想在空格和字符"'();,{ {1}}和|,除非使用&进行转义。

一些例子如下:

\

为此,我写了正则表达式:

"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"]

它适用于所有其他情况,除了一个:

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

如何修改正则表达式以获得预期结果?

我不想使用>>> re.findall(r'''(?:[^\s"'();|&]+|\\.)+''', r'hello\;world') ['hello\\', 'world'] ;上面的正则表达式是一个更大的正则表达式的一部分,用于使用re.split()对编程语言进行标记。

1 个答案:

答案 0 :(得分:2)

您的[^\s"'();|&]+模式部分会抓取\,然后\\.无法正确匹配转义的字符。

您可以使用

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

请参阅regex demo

此处,模式匹配任何转义字符的一次或多次重复(如果使用re.DOTALLre.S,甚至包括换行符),或除空格之外的任何字符{{1} },"'();|&

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("-------------")
相关问题