0

I am trying to us python re to split strings on multiple delimiters, but it screams about my escaped backslash character.

I am not sure what to change as when I looked for escaping backslash in python, this is what I was shown is correct...

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)
Scorb
  • 1,654
  • 13
  • 70
  • 144

3 Answers3

7

Your first backslash is escaping the second at the level of the string literal. But the regex engine needs that backslash escaped also, since it's a special character for regex too.

Use a "raw" string literal (e.g. r' |/|\\') or quadruple backslash.

Chris
  • 6,805
  • 3
  • 35
  • 50
3

try

import re
def get_asset_str(in_str):
    split = re.split(r' |/|\\' , in_str)
LNT
  • 124
  • 3
1

This should do what you want:

import re

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

results:

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

Need to quad escape the backslash. Or use raw input (I like this better but that's just me)

sniperd
  • 5,124
  • 6
  • 28
  • 44