Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Skip Consecutive Separator In Split

I need to split a string by "\" separator. But i have to skip the consecutive occurrences. More precisely, for my goal "//sensor1" needs to be read like '/sensor1'.

import re
a = "root/master/sensors//sensor1/value"
re.split("/+", a)

So i need to obtain:

['root', 'master', 'sensors//sensor1', 'value']

I tried that code, but maybe i did an error in the regex expression.

like image 360
paolo2988 Avatar asked Aug 18 '15 11:08

paolo2988


2 Answers

x="root/master/sensors//sensor1/value"
print re.split(r"(?<!\/)\/",x)

You can use lookbehind here to make sure only one / splits.

Output:['root', 'master', 'sensors', '/sensor1', 'value']

like image 170
vks Avatar answered Sep 28 '22 09:09

vks


You can use a positive look behind to split the text based on the forward slashes that precede by a word character :

>>> re.split(r"(?<=\w)/", a)
['root', 'master', 'sensors', '/sensor1', 'value']
like image 28
Mazdak Avatar answered Sep 28 '22 09:09

Mazdak