473,783 Members | 2,350 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 14977
"J. W. McCall" <jm*****@housto n.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*****@housto n.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.ma n> 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.spl it('"'))] 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.spl it('"'))] ifr] or [''] ['""', '""'] x='""'
[r for r in [(i%2 and ['"'+z+'"'] or [z.strip()])[0] for i,z in enumerate(x.spl it('"'))] ifr] or [''] ['""'] x=''
[r for r in [(i%2 and ['"'+z+'"'] or [z.strip()])[0] for i,z in enumerate(x.spl it('"'))] ifr] or [''] ['']
[(i%2 and ['"'+z+'"'] or [z.strip()])[0] for i,z in enumerate(x.spl it('"'))]

['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.se tParseAction( 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
1529
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"; $quote = "I would love to change the world, but they won't give me the source code!' - Unknown";
13
1377
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 JS. Here are two examples (not JS): 1. http://www.cheeseman.com/Density-Calculator.asp 2.
1
1202
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 general consensus on how to proceed from here. Thank you in advance for anyone who takes the time to reply... I am upgrading a VB4.0 program for a client who distributes it to its reps worldwide. We are not at the point where we want to make...
3
3974
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 "/Library/Frameworks/Python.framework/Versions/2.4//lib/python2.4/urllib.py", line 1117, in quote res = map(safe_map.__getitem__, s)
8
1395
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 reguister with email address and password if password is lost
4
3004
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
4444
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 is added to a form/cart like page that the user can then submit for a quote request, Any Ideas?
3
2385
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 = "http://finance.yahoo.com/q?s=MSFT" Set objXMLHTTP = CreateObject("Microsoft.XMLHTTP") objXMLHTTP.open "GET",strUrlAddress, false
6
7137
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
2795
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 free. Ajax based solution refreshes data at configured time interval and you don't have to wait for your favourite stock to appear in ticker. You have all latest view auto updated and for all the stocks at one go. In my approach i am using ajax...
0
9643
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9480
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10313
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10081
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9946
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7494
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6735
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5378
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3643
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.