Python re.split()转义反斜杠

时间:2017-09-26 19:16:21

标签: python regex

我正在尝试让我们在多个分隔符上拆分字符串python,但它对我的转义反斜杠字符感到尖叫。

我不确定要改变什么,因为当我在python中寻找转义反斜杠时,这就是我所展示的正确...

import re
def get_asset_str(in_str):
    split = re.split(' |/|\\' , in_str)



Traceback (most recent call last):
  File "AssetCheck.py", line 15, in <module>
    get_asset_str(line)
  File "AssetCheck.py", line 4, in get_asset_str
    split = re.split(' |/|\\' , in_str)
  File "C:\Python27\lib\re.py", line 167, in split
    return _compile(pattern, flags).split(string, maxsplit)
  File "C:\Python27\lib\re.py", line 244, in _compile
    raise error, v # invalid expression
sre_constants.error: bogus escape (end of line)

3 个答案:

答案 0 :(得分:5)

你的第一个反斜杠是在字符串文字的级别转义第二个。但是正则表达式引擎也需要 反斜杠转义,因为它也是正则表达式的特殊字符。

使用&#34; raw&#34;字符串文字(例如r' |/|\\')或四倍反斜杠。

答案 1 :(得分:2)

import re
def get_asset_str(in_str):
    split = re.split(r' |/|\\' , in_str)

答案 2 :(得分:0)

这应该做你想要的:

import re

in_str = """Hello there\good/morning"""
thelist = re.split(' |/|\\\\' , in_str)
print (thelist)

结果:

['Hello', 'there', 'good', 'morning']

需要四方逃避反斜杠。或者使用原始输入(我更喜欢这个,但那只是我)