473,324 Members | 2,254 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,324 software developers and data experts.

How can we get to the end of a quote inside a string

Hi all,
Suppose I have a string which contains quotes inside quotes -
single and double quotes interchangeably -
s = "a1' b1 " c1' d1 ' c2" b2 'a2"
I need to start at b1 and end at b2 - i.e. I have to parse the
single quote strings from inside s.

Is there an existing string quote parser which I can use or
should I write a parser myself?

If somebody could help me on this I would be much obliged.

Regards
kR/\/
Aug 31 '08 #1
3 1499
On Sun, 31 Aug 2008 07:29:26 -0700 (PDT), ra********@gmail.com wrote:
Suppose I have a string which contains quotes inside quotes -
single and double quotes interchangeably -
s = "a1' b1 " c1' d1 ' c2" b2 'a2"
>>s = "a1' b1 " c1' d1 ' c2" b2 'a2"
File "<stdin>", line 1
s = "a1' b1 " c1' d1 ' c2" b2 'a2"
^
SyntaxError: invalid syntax
>>>
Writing a small parser for your needs shouldn't be that hard.
To some extent you can use regular expressions:
>>re.findall(re.compile("\".*?\""), s)
['" c1\' d1 \' c2"']
>>re.findall(re.compile("\'.*?\'"), s)
['\' b1 " c1\'', '\' c2" b2 \'']
>>>
but it won't work in all cases. You can read more here:
http://www.gnosis.cx/TPiP/

--
Regards,
Wojtek Walczak,
http://tosh.pl/gminick/
Aug 31 '08 #2
On 2008-08-31, ra********@gmail.com <ra********@gmail.comwrote:
Hi all,
Suppose I have a string which contains quotes inside quotes -
single and double quotes interchangeably -
s = "a1' b1 " c1' d1 ' c2" b2 'a2"
I need to start at b1 and end at b2 - i.e. I have to parse the
single quote strings from inside s.

Is there an existing string quote parser which I can use or
should I write a parser myself?

If somebody could help me on this I would be much obliged.
You could use a combination of split and join in this case.

#use a single quote as a seperator to split the string is a list of substrings
ls = s.split("'")

#remove what comes before the first and after the last single quote
ls = ls[1:-1]

#reassemble the string between the outermost single quotes.
s = "'".join(ls)

#strip spaces in front and after if you wish
s = s.strip()

--
Antoon Pardon
Sep 2 '08 #3
On Aug 31, 9:29*am, rajmoha...@gmail.com wrote:
Hi all,
* * Suppose I have a string which contains quotes inside quotes -
single and double quotes interchangeably -
*s = "a1' b1 " c1' d1 ' c2" b2 'a2"
* * *I need to start at b1 and end at b2 - i.e. I have to parse the
single quote strings from inside s.
Pyparsing defines a helper method called nestedExpr - typically it is
used to find nesting of ()'s, or []'s, etc., but I was interested to
see if I could use nestedExpr to match nested ()'s, []'s, AND {}'s all
in the same string (like we used to do in our algebra class to show
nesting of higher levels than parens - something like "{[a + 3*(b-c)]
+ 7}" - that is, ()'s nest within []'s, and []'s nest within {}'s).
This IS possible, but it uses some advanced pyparsing methods. I
adapted this example to map to your case - this was much simpler, as
""s nest within ''s, and ''s nest within ""s. I still keep a stack of
previous nesting, but I'm not sure this was absolutely necessary.
Here is the working code with your example:

from pyparsing import Forward, oneOf, NoMatch, Literal, CharsNotIn,
nestedExpr

# define special subclass of Forward, that saves previous contained
# expressions in a stack
class ForwardStack(Forward):
def __init__(self):
super(ForwardStack,self).__init__()
self.exprStack = []
self << NoMatch()
def __lshift__(self,expr):
self.exprStack.append(self.expr)
super(ForwardStack,self).__lshift__(expr)
return self
def pop(self):
self.expr = self.exprStack.pop()

# define the grammar
opening = ForwardStack()
closing = ForwardStack()
opening << oneOf(["'", '"'])
closing << NoMatch()
matchedNesting = nestedExpr(opening, closing, CharsNotIn('\'"'),
ignoreExpr=None)

# define parse-time callbacks
alternate = {'"':"'", "'":'"'}
def pushAlternate(t):
# closing expression should match the current opening quote char
closing << Literal( t[0] )
# if we find the other opening quote char, it is the beginning of
# a nested quote
opening << Literal( alternate[ t[0] ] )
def popClosing():
closing.pop()
opening.pop()
# when these expressions match, the parse action will be called
opening.setParseAction(pushAlternate)
closing.setParseAction(popClosing)

# parse the test string
s = """ "a1' b1 " c1' d1 ' c2" b2 'a2" """

print matchedNesting.parseString(s)[0]
Prints:

['a1', [' b1 ', [' c1', [' d1 '], ' c2'], ' b2 '], 'a2']
-- Paul
Sep 2 '08 #4

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

Similar topics

4
by: Don Crossman | last post by:
Can someone tell me how to get this line to work? document.write (" <input type='button' value='Make this your home page' onclick='this.style.behavior="url(#default#homepage)";...
1
by: Venkat | last post by:
Hi All, I am getting unusual compile errors when i declare a vector as a private member of a class in .h file, but if i declare the same in .cpp file inside the definition of a function which...
18
by: Bryan Parkoff | last post by:
"#define" can only be inside the global scope before main() function. "#if" can be tested after "#define" is executed. The problem is that "#define" can't be inside main() function. I do not wish...
1
by: Jim P. | last post by:
I'm having trouble returning an object from an AsyncCallback called inside a threaded infinite loop. I'm working on a Peer2Peer app that uses an AsyncCallback to rerieve the data from the remote...
0
by: Jai | last post by:
Hi, Somebody please tell me how to bind(two way) a checkboxlist with objectdatasource if the checkboxlist is inside a formview..... Code of FormView is like this::--- <asp:FormView...
0
by: Jai | last post by:
Hi, Somebody please tell me how to bind(two way) a checkboxlist with objectdatasource if the checkboxlist is inside a formview..... Code of FormView is like this::--- <asp:FormView...
3
by: =?Utf-8?B?QW5keQ==?= | last post by:
Hello, I'm trying to use a string type variable inside a class. I can do this fine with no problems when the class is inside a cpp file simply by adding #include <string>. However, my program has...
5
by: sgurukrupagmailcom | last post by:
Hi, I haven't come accross an elegant solution to a design problem that I show below. Have a look at the piece of code here: class Exc { Exc () { System.out.println ("Haribol"); }
1
by: JavaJon | last post by:
Hello, I'm Jon. I've recently picked up Java after using a "gimmick" programming language called GML ( Game Maker Language ). I've read a lot of tutorials and even a Java for Dummies *.pdf book....
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

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.