Reputation: 5492
I have python string as follows
mystring = "copy "d:\Progrm Files" "c:\Progrm Files\once up on a time""
how can I split this string to
mylist = [copy,d:\Progrm Files,c:\Progrm Files\once up on a time]
When I tried to use mysring.split(" ")
the spaces Progrm Files
and once up on a time
are also getting split.
Upvotes: 0
Views: 206
Reputation: 43437
this regex catches what you want:
import re
mystring = "copy \"d:\Progrm Files\" \"c:\Progrm Files\once up on a time\""
m = re.search(r'([\w]*) ["]?([[\w]:\\[\w\\ ]+)*["]? ["]?([[\w]:\\[\w\\ ]+)*["]?', mystring)
print m.group(1)
print m.group(2)
print m.group(3)
>>>
copy
d:\Progrm Files
c:\Progrm Files\once up on a time
Upvotes: 1
Reputation: 1121346
You want to take a look at the shlex
module, the shell lexer. It specializes in splitting command lines such as yours into it's constituents, including handling quoting correctly.
>>> import shlex
>>> command = r'copy "d:\Program Files" "c:\Program Files\once up on a time"'
>>> shlex.split(command)
['copy', 'd:\\Program Files', 'c:\\Program Files\\once up on a time']
Upvotes: 9