473,769 Members | 1,805 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Quote aware split

Hi,

After trawling through the archives for a simple quote aware split
implementation (ie string.split-alike that only splits outside of
matching quote) and coming up short, I implemented a quick and dirty
function that suits my purposes.

It's ugly and it doesn't use a stack, it only supports a single
character as a 'sep' function, only supports one type of quote (ie '
or " but not both), but it does the job, and since there have been a
few appeals over the years for something of this sort I have decided
to post what I have:

--- BEGIN ---
#!/usr/bin/env python

def qsplit(chars, sep, quote="'"):
""" Quote aware split """
qcount = 0
splitpoints = [-1] # ie. seperator char found before first letter ;)
for index, c in enumerate(chars ):
if c is quote:
qcount += 1
if c is sep and qcount % 2 == 0:
splitpoints.app end(index)

# slice chars by splitpoints *omitting the separator*
slices = [chars[splitpoints[i]+1:splitpoints[i+1]]
for i in range(len(split points)-1)]

# last slice will be of the form chars[last:] which we couldnt do above
slices.append(c hars[splitpoints[-1]+1:])
return slices
if __name__ == "__main__":
test = "This is gonna be in quotes ';' and this is not; lets see
how we split"

test2 = """
A more complex example; try this on for size:

create function blah '
split me once;
split me twice; '
end;
'one more time;'
and again;
"""
print "*--split--*".join(qsplit( test, ';'))
print "*--split--*".join(qsplit( test2, ';'))

# vim:tabstop=4:s hiftwidth=4:exp andtab
--- END ---

Regards,
Ondrej Baudys
May 16 '07 #1
3 1764
Ondrej Baudys wrote:
Hi,

After trawling through the archives for a simple quote aware split
implementation (ie string.split-alike that only splits outside of
matching quote) and coming up short, I implemented a quick and dirty
function that suits my purposes.
<snip/>

Maybe using the csv module together with cStringIO would be more
straightforward .

Diez
May 16 '07 #2
On May 16, 10:50 am, "Ondrej Baudys" <obau...@gmail. comwrote:
# last slice will be of the form chars[last:] which we couldnt do above
Who are "we"? Here's another version with the "couldn't do" problem
fixed and a few minor enhancements:

def qsplit2(chars, sep=",", quote="'"):
""" Quote aware split """
assert sep != quote
can_split = True
splitpoints = [-1] # ie. separator char found before first
letter ;)
for index, c in enumerate(chars ):
if c == quote:
can_split = not can_split
elif c == sep and can_split:
splitpoints.app end(index)
if not can_split:
raise ValueError("Unt erminated quote")
splitpoints.app end(len(chars))
# slice chars by splitpoints *omitting the separator*
slices = [chars[splitpoints[i]+1:splitpoints[i+1]]
for i in range(len(split points)-1)]
return slices

Cheers,
John

May 16 '07 #3
"Ondrej Baudys" <ob*****@gmail. comwrote in message
news:ma******** *************** *************** *@python.org...
Hi,

After trawling through the archives for a simple quote aware split
implementation (ie string.split-alike that only splits outside of
matching quote) and coming up short, I implemented a quick and dirty
function that suits my purposes.
Take a look at pyparsing--you'll like it I think.
esp. http://pyparsing.wikispaces.com/Examples

--Tim Arnold
May 16 '07 #4

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

Similar topics

5
31178
by: Stu Cazzo | last post by:
I have the following: String myStringArray; String myString = "98 99 100"; I want to split up myString and put it into myStringArray. If I use this: myStringArray = myString.split(" "); it will split myString up using the delimiter of 1 space so that
11
2507
by: Carlos Ribeiro | last post by:
Hi all, While writing a small program to help other poster at c.l.py, I found a small inconsistency between the handling of keyword parameters of string.split() and the split() method of strings. I wonder if someone else had ever stumbled on it before, and if it has a good reason to work like it is. Both implementations take two parameters: the separator character and the max number of splits (maxsplit). However, string.split() accept
9
4350
by: Will McGugan | last post by:
Hi, I'm curious about the behaviour of the str.split() when applied to empty strings. "".split() returns an empty list, however.. "".split("*") returns a list containing one empty string. I would have expected the second example to have also returned an empty
7
14977
by: J. W. McCall | last post by:
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'
2
12838
by: SL_McManus | last post by:
Hi All; I am fairly new to Perl. I have a file with close to 3000 lines that I would like to split out in a certain way. I would like to put the record type starting in column 1 for 2 spaces, the employer code in column 23 for 29 spaces and employer description in column 53 for 30 spaces. I have tried modifying an existing file with no real success. I haven't found anything that specifically answers my question. Any guidance would be...
7
9586
by: Ahmad A. Rahman | last post by:
Hi All, I have a string as and I want to split the string, which will turn into an array of: Arr = "1"; Arr = "two"; Arr = "three"; Arr = "fo""ur"; Arr = "fi,ve";
4
5789
by: Itzik | last post by:
can i split this string string str = "aa a - bb-b - ccc" with this delimiter string del = " - " i want recieve 3 items : "aa a" , "bb-b" , "ccc"
5
1774
by: lgbjr | last post by:
Hello All, I have the following type of string: "X:Y\Z.exe" "123" What I need is an array of strings with the information from within each set of quotes. I was trying to use a Regex.Split, but I can't figure out how to escape a quote. The closest I got was Regex.split(String,"(\"")"), which gives me an array of strings: "X:Y\Z.exe
5
5877
by: kurt sune | last post by:
The code: Dim aLine As String = "cat" & vbNewLine & "dog" & vbNewLine & "fox" & vbNewLine Dim csvColumns1 As String() = aLine.Split(vbNewLine, vbCr, vbLf) Dim csvColumns2 As String() = Microsoft.VisualBasic.Strings.Split(aLine, vbNewLine, -1, CompareMethod.Binary)
0
9423
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
10212
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
9995
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,...
1
7410
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
6674
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
5304
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...
0
5447
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3962
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2815
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.