How to split string on '/' delimiter but prevent splitting when '/ ' occurs just after ' \ '
I am trying to split string data using Python which is delimited by the '/' character. The problem is that the string could have multiple occurrence of the '/' character but I want to split it only using '/' and not using '\/'开发者_StackOverflow中文版
For example, I am trying to split the string '1\/2/CD' into '1\/2' and 'CD'
Use a negative lookbehind assertion in the regexp:
>>> re.split(r'(?<!\\)/', r'1\/2/CD')
['1\\/2', 'CD']
From the docs:
(?<!...)
Matches if the current position in the string is not preceded by a match for
...
. This is called a negative lookbehind assertion. Similar to positive lookbehind assertions, the contained pattern must only match strings of some fixed length. Patterns which start with negative lookbehind assertions may match at the beginning of the string being searched.
This works when you have the first slice empty:
>>> re.split(r'(?<!\\)/', r'/CD')
['', 'CD']
You can use the split method of the regex object, just split on /
which isn't following a \
(using negative lookbehind):
import re
str = u'1\\/2/CD'
re.split(r'(?<!\\)/',str)
If the delimiter is always at the end of the string you can user str.rpartition:
>>> print u'1\/2/CD'.rpartition('/') (u'1\\/2', u'/', u'CD')
精彩评论