473,756 Members | 2,721 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 1524
On Sun, 31 Aug 2008 07:29:26 -0700 (PDT), ra********@gmai l.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********@gmai l.com <ra********@gma il.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...@gmai l.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(Fo rward):
def __init__(self):
super(ForwardSt ack,self).__ini t__()
self.exprStack = []
self << NoMatch()
def __lshift__(self ,expr):
self.exprStack. append(self.exp r)
super(ForwardSt ack,self).__lsh ift__(expr)
return self
def pop(self):
self.expr = self.exprStack. pop()

# define the grammar
opening = ForwardStack()
closing = ForwardStack()
opening << oneOf(["'", '"'])
closing << NoMatch()
matchedNesting = nestedExpr(open ing, 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.setPars eAction(pushAlt ernate)
closing.setPars eAction(popClos ing)

# 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
2041
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)"; this.setHomePage("http://www.somewhere.com");' />"); Seems no matter what I try, it either throws an error (expected ')'), or just does nothing. It would seem that escaping is not the answer in this case (it didn't work).
1
2947
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 is a member of the same class it is working fine. Here is my .h file #include <wtypes.h>
18
8927
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 to create multiple functions which they look almost identical in C++ source code. The C++ compiler should be able to compile one Test() function into two almost identical functions before they are translated into the machine language object. ...
1
5224
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 peer. I have no problem connecting the peers and streaming Network Streams. When the incoming data is finished recieving, I act upon it. This works great as long as all of the code is inside my form. I want to build the networking code into a...
0
2176
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 ID="FormView1" runat="server" DataSourceID="ObjectDataSource1"> <EditItemTemplate>
0
2417
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 ID="FormView1" runat="server" DataSourceID="ObjectDataSource1"> <EditItemTemplate>
3
1748
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 the class specification in a header file and the functions in a cpp file, for better organisation and linking. When I specify a string in the class definition in the header file I get "syntax error : missing ';' before identifier 'avOwnerName'"...
5
4048
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
3043
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. The basics are similar to what I'm accustomed to but there's still some confusion. I'm currently playing around with how the static, public, protected etc things work and I stumbled upon a problem. In the following copypasted code ( a tutorial I...
0
9456
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
10034
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...
0
9872
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9713
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...
0
8713
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7248
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...
1
3805
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
2
3358
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2666
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.