473,219 Members | 2,004 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,219 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 1492
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: veera ravala | last post by:
ServiceNow is a powerful cloud-based platform that offers a wide range of services to help organizations manage their workflows, operations, and IT services more efficiently. At its core, ServiceNow...
3
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 3 Jan 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). For other local times, please check World Time Buddy In...
0
by: jianzs | last post by:
Introduction Cloud-native applications are conventionally identified as those designed and nurtured on cloud infrastructure. Such applications, rooted in cloud technologies, skillfully benefit from...
0
by: mar23 | last post by:
Here's the situation. I have a form called frmDiceInventory with subform called subfrmDice. The subform's control source is linked to a query called qryDiceInventory. I've been trying to pick up the...
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
2
by: jimatqsi | last post by:
The boss wants the word "CONFIDENTIAL" overlaying certain reports. He wants it large, slanted across the page, on every page, very light gray, outlined letters, not block letters. I thought Word Art...
0
Git
by: egorbl4 | last post by:
Скачал я git, хотел начать настройку, а там вылезло вот это Что это? Что мне с этим делать? ...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....

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.