2017-09-26 212 views
-1

我想我們python re拆分字符串在多個分隔符,但它尖叫關於我逃脫反斜槓字符。Python re.split()轉義反斜槓

我不知道該怎麼當我看着在蟒蛇逃脫反斜線改變,這就是我表現出是正確的......

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) 
+0

這是因爲它正在尋找你正在被轉義的正則表達式中的字符。 –

+4

使用一個原始字符串:'r'|/| \\''和更好的替代單個字符的替代,使用字符類:'r'[/ \\]'' –

+0

您需要''|/| \ \\\'' –

回答

5

你的第一個反斜槓在字符串文字的級別逃避第二個。但正則表達式引擎需要反斜槓也逃脫,因爲它也是一個正則表達式的特殊字符。

使用「原始」字符串文字(例如r' |/|\\')或四重反斜槓。

2

嘗試

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

這應該做你想要什麼:

import re 

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

結果:

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

需要四轉義反斜線。或者使用原始輸入(我喜歡這個更好,但這只是我)