分割字符串时如何使用re特殊字符?

时间:2014-09-01 18:41:16

标签: python regex python-2.7

假设我有这个名为string的变量。

string = "Hello(There|World!!"

由于我想分割多个分隔符,我使用re.split()来完成这项工作。不幸的是,此字符串包含re模块使用的特殊字符。我不想使用re.escape(),因为这也会逃避感叹号。如何在不使用re的情况下拆分re.escape()个特殊字符?

2 个答案:

答案 0 :(得分:2)

使用character class定义要拆分的字符。

我认为你可能想保留这些惊叹号。如果是这种情况..

>>> s = "Hello(There|World!!"
>>> re.split(r'[(|]+', s)
['Hello', 'There', 'World!!']

如果你想分开感叹号。

>>> s = "Hello(There|World!!"
>>> re.split(r'[(|!]+', s)
['Hello', 'There', 'World', '']

如果你想分开其他角色,只需将它们添加到你的班级。

>>> s = "Hello(There|World!!Hi[There]"
>>> re.split(r'[(|!\[\]]+', s)
['Hello', 'There', 'World', 'Hi', 'There', '']

然后使用filter删除列表中的None元素。

答案 1 :(得分:0)

 re.split(r"\(|\||!",x)

Output:['Hello', 'There', 'World', '', '']

您可以使用多个分隔符进行拆分。

相关问题