473,394 Members | 1,770 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

Quote-aware string splitting

Hello,

I need to split a string as per string.strip(), but with a modification:
I want it to recognize quoted strings and return them as one list item,
regardless of any whitespace within the quoted string.

For example, given the string:

'spam "the life of brian" 42'

I'd want it to return:

['spam', 'the life of brian', '42']

I see no standard library function to do this, so what would be the most
simple way to achieve this? This should be simple, but I must be tired
as I'm not currently able to think of an elegant way to do this.

Any ideas?

Thanks,

J. W. McCall
Jul 19 '05 #1
7 14937
"J. W. McCall" <jm*****@houston.rr.com> writes:

I need to split a string as per string.strip(), but with a
modification: I want it to recognize quoted strings and return them as
one list item, regardless of any whitespace within the quoted string.

For example, given the string:

'spam "the life of brian" 42'

I'd want it to return:

['spam', 'the life of brian', '42']

I see no standard library function to do this, so what would be the
most simple way to achieve this? This should be simple, but I must be
tired as I'm not currently able to think of an elegant way to do this.

Any ideas?


How about the csv module? It seems like it might be overkill, but it
does already handle that sort of quoting
import csv
csv.reader(['spam "the life of brian" 42'], delimiter=' ').next()

['spam', 'the life of brian', '42']

Jul 19 '05 #2
> "J. W. McCall" <jm*****@houston.rr.com> writes:

I need to split a string as per string.strip(), but with a
modification: I want it to recognize quoted strings and return them as
one list item, regardless of any whitespace within the quoted string.
For example, given the string:

'spam "the life of brian" 42'

I'd want it to return:

['spam', 'the life of brian', '42']

I see no standard library function to do this, so what would be the
most simple way to achieve this? This should be simple, but I must be tired as I'm not currently able to think of an elegant way to do this.
Any ideas?
How about the csv module? It seems like it might be overkill, but it
does already handle that sort of quoting
>>> import csv
>>> csv.reader(['spam "the life of brian" 42'], delimiter='

').next() ['spam', 'the life of brian', '42']

I don't know if this is as good as CSV's splitter, but it works
reasonably well for me:

import re
regex = re.compile(r'''
'.*?' | # single quoted substring
".*?" | # double quoted substring
\S+ # all the rest
''', re.VERBOSE)

print regex.findall('''
This is 'single "quoted" string'
followed by a "double 'quoted' string"
''')

George

Jul 19 '05 #3
J. W. McCall wrote:
For example, given the string:

'spam "the life of brian" 42'

I'd want it to return:

['spam', 'the life of brian', '42']


The .split() method of strings can take a substring, such as a quotation
mark, as a delimiter. So a simple solution is:
x = 'spam "the life of brian" 42'
[z.strip() for z in x.split('"')]

['spam', 'the life of brian', '42']
Jeffrey
Jul 19 '05 #4
> import re
regex = re.compile(r'''
'.*?' | # single quoted substring
".*?" | # double quoted substring
\S+ # all the rest
''', re.VERBOSE)


Oh, and if your strings may span more than one line, replace re.VERBOSE
with re.VERBOSE | re.DOTALL.

George

Jul 19 '05 #5
On Mon, 25 Apr 2005 19:40:44 -0700, Jeffrey Froman <je*****@fro.man> wrote:
J. W. McCall wrote:
For example, given the string:

'spam "the life of brian" 42'

I'd want it to return:

['spam', 'the life of brian', '42']


The .split() method of strings can take a substring, such as a quotation
mark, as a delimiter. So a simple solution is:
x = 'spam "the life of brian" 42'
[z.strip() for z in x.split('"')]['spam', 'the life of brian', '42']

x = ' sspam " ssthe life of brianss " 42'
[z.strip() for z in x.split('"')] ['sspam', 'ssthe life of brianss', '42']

Oops, note some spaces inside quotes near ss and missing double quotes in result.
Maybe (not tested beyond what you see):
[r for r in [(i%2 and ['"'+z+'"'] or [z.strip()])[0] for i,z in enumerate(x.split('"'))] if r] or [''] ['sspam', '" ssthe life of brianss "', '42'] x = ' "" "" '
[r for r in [(i%2 and ['"'+z+'"'] or [z.strip()])[0] for i,z in enumerate(x.split('"'))] ifr] or [''] ['""', '""'] x='""'
[r for r in [(i%2 and ['"'+z+'"'] or [z.strip()])[0] for i,z in enumerate(x.split('"'))] ifr] or [''] ['""'] x=''
[r for r in [(i%2 and ['"'+z+'"'] or [z.strip()])[0] for i,z in enumerate(x.split('"'))] ifr] or [''] ['']
[(i%2 and ['"'+z+'"'] or [z.strip()])[0] for i,z in enumerate(x.split('"'))]

['sspam', '" ssthe life of brianss "', '42']
Regards,
Bengt Richter
Jul 19 '05 #6
Quoted strings are surprisingly stateful, so that using a parser isn't
totally out of line. Here is a pyparsing example with some added test
cases. Pyparsing's quotedString built-in handles single or double
quotes (if you don't want to be this permissive, there are also
sglQuotedString and dblQuotedString to choose from), plus escaped quote
characters.

The snippet below includes two samples. The first 3 lines give the
equivalent to other suggestions on this thread. It is followed by a
slightly enhanced version that strips quotation marks from any quoted
entries.

-- Paul
(get pyparsing at http://pyparsing.sourceforge.net)
==========
from pyparsing import *
test = r'''spam 'it don\'t mean a thing' "the life of brian"
42 'the meaning of "life"' grail'''
print OneOrMore( quotedString | Word(printables) ).parseString( test )

# strip quotes during parsing
def stripQuotes(s,l,toks):
return toks[0][1:-1]
quotedString.setParseAction( stripQuotes )
print OneOrMore( quotedString | Word(printables) ).parseString( test )
==========

returns:
['spam', "'it don\\'t mean a thing'", '"the life of brian"', '42',
'\'the meaning of "life"\'', 'grail']
['spam', "it don\\'t mean a thing", 'the life of brian', '42', 'the
meaning of "life"', 'grail']

Jul 19 '05 #7
Bengt Richter wrote:
Oops, note some spaces inside quotes near ss and missing double quotes in
result.


And here I thought the main problem with my answer was that it didn't split
unquoted segments into separate words at all! Clearly I missed the
generalization being sought, and a more robust solution is in order.
Fortunately, others have been forthcoming with them.

Thank you,
Jeffrey
Jul 19 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: orbstra | last post by:
<?php //Variables //Quotes $quote = "'If at first you don't succeed; call it version 1.0' - T-Shirt"; $quote = "Microsoft: 'You`ve got questions. We've got dancing paperclips.' - Unknown";...
13
by: Shaun Furlong | last post by:
I'm new to this group - and newsgroups in general - so I aplogize if I'm out of line here... I'm a web designer, but not proficient in JS. I need a quote for a simple "Density Calculator" in...
1
by: jmar | last post by:
I posted on this topic a while back and received some good responses. However, I have better insight into what I'm looking to do so I am tapping the wealth of experience here again hoping to find a...
3
by: nyenyec | last post by:
urllib.quote chokes on unicode in 2.4.4. 2.4.4 (#1, Oct 18 2006, 10:34:39) Traceback (most recent call last): File "<stdin>", line 1, in ? File...
8
by: plemon | last post by:
alright here is what it is: a computer site where customers build custom system by selecting from forms and radio buttons. what is needed: a database (MySQL) with php basicly... 1 users...
4
by: mtugnoli | last post by:
This is my XML file <?xml version="1.0" encoding="utf-8"?> <index> <folder Name="Test1"> <folder Name="Test2"> <files> <file Name="After You've Gone.mp3"/> <file Name="Prova.mp3"/> </files>
6
by: Anonymous Chief | last post by:
Hi, I need help with a script I can add to my products on an html page. What I want is to assign a number to each product or name such that when I click on the link below the product image, it...
3
by: yuvalbra | last post by:
Does anyone know how to implement a stock quote using ASP on a website? Any sample code or components, etc., would be appreciated. I try this but got error 500 on page strURL =...
6
by: Luke Davis | last post by:
I can't figure this out, why am I getting ")" expected and ";" expected on this line? Response.Write("<input type=""hidden"" name=""item_number"" value="".COM, MLSNumber"">"); - L
3
by: Rajesh | last post by:
Have you guys wanted to have stock tickers on ur desktop/ web pages, but can't use applets as they were heavy, too much configuration than here is one approach and light weight solution all for...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.