Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What would be a good way to deal with backslash escaped characters?

I have a string in the following format;

s="part1,part2,part3,part4"

I can split the string into pieces by just invoking the s.split(",") command.

Now, the question is what if I have a backslash escaped comma in the string? Assuming I have the following string,

s="part1,part2,pa\\,rt3,part4"

I'd like to be able to get ["part1","part2","pa,rt3","part4"] as the result.

What I initially thought was to replace the \, with a non-existent string, then split the string by using the split command and replace the non-existent string with a comma.

Can you think of a better way to deal with this problem?

like image 279
Utku Zihnioglu Avatar asked Dec 09 '22 11:12

Utku Zihnioglu


1 Answers

Replacing it with a non-existing string is a nice option.

And otherwise, you could use a regular expression with a negative lookbehind like this:

re.split(r'(?<!\\),', 'part1,part2,pa\\,rt3,part4')
like image 58
Wolph Avatar answered Dec 28 '22 23:12

Wolph