regular expression for space seperated quoted string

Padraig Brady Padraig at Linux.ie
Wed Sep 11 13:35:11 CEST 2002


Padraig Brady wrote:
> Hi, I'm trying to split a string that is seperated
> by spaces and also contains double quoted words which
> can contain spaces:
> 
> For e.g. using: re.split('[ ]*"?([^"]*)"?[ ]*', s1)
> on this string: s1='1 "2" "thre e"'
> gives:          ['', '1 ', '', '2', '', 'thre e', '']
> 
> Problem with this is the '' entries, but this isn't too bad.
> 
> However using the above re with: s2='1 2 "th ree"'
> I get:                           ['', '1 2 ', '', 'th ree', '']
> 
> any ideas?

Well this one does better:
re.split('[ ]+|"([^"]*)"', string)

It does leave '' and None entries in the list,
but I can remove these easily.

I presume there is something more elegant.

Pádraig.




More information about the Python-list mailing list