0

First: I know there are much examples on stackoverflow for these kind of problems but i have not found the exact result I need.

I have the following program

import re

def magic(string):     
    return [i.strip('"').strip("'") for i in re.split(r'(\s+|(?<!\\)".*?(?<!\\)"|(?<!\\)\'.*?(?<!\\)\')', string) if i.strip()] 

myString = """ function_name param1 param 2 "param 3" "param \"4 lorem ipsum\""  'param 5' 'param \'6 lorem ipsum\'' """
print magic(myString)

I expected this as output:

['function_name', 'param1', 'param', '2', 'param 3', 'param "4 lorem ipsum"', 'param 5', "param '6 lorem ipsum'"]

But I get this:

['function_name', 'param1', 'param', '2', 'param 3', 'param ', '4', 'lorem', 'ipsum', '', 'param 5', 'param ', '6', 'lorem', 'ipsum', '']

So Python has problems with the escaping. When I trible escape my strings..

myString = """ function_name param1 param 2 "param 3" "param \\\"4 lorem ipsum\\\""  'param 5' 'param \\\'6 lorem ipsum\\\'' """

I get this:

['function_name', 'param1', 'param', '2', 'param 3', 'param \\"4 lorem ipsum\\', 'param 5', "param \\'6 lorem ipsum\\"]

=> Some quotes disappear and anyway I dont want to write three \ to escape a quote.

I hope someone can help me to improve this function

serrulez
  • 1
  • 3

0 Answers0