473,725 Members | 2,168 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Checking if string inside quotes?

Hello:

If I have a long string (such as a Python file).
I search for a sub-string in that string and find it.
Is there a way to determine if that found sub-string is
inside single-quotes or double-quotes or not inside any quotes?
If so how?

Thanks in advance:
Michael Yanowitz

May 9 '07 #1
4 12769
On May 9, 1:39 pm, "Michael Yanowitz" <m.yanow...@kea rfott.comwrote:
Hello:

If I have a long string (such as a Python file).
I search for a sub-string in that string and find it.
Is there a way to determine if that found sub-string is
inside single-quotes or double-quotes or not inside any quotes?
If so how?

Thanks in advance:
Michael Yanowitz
I think the .find() method returns the index of the found string. You
could check one char before and then one char after the length of the
string to see. I don't use regular expressions much, but I'm sure
that's a more elegant approach.

This will work. You'll get in index error if you find the string at
the very end of the file.

s = """
foo
"bar"
"""
findme = "foo"
index = s.find(findme)

if s[index-1] == "'" and s[index+len(findm e)] == "'":
print "single quoted"
elif s[index-1] == "\"" and s[index+len(findm e)] == "\"":
print "double quoted"
else:
print "unquoted"

~Sean

May 9 '07 #2
On May 9, 4:31 pm, "Michael Yanowitz" <m.yanow...@kea rfott.comwrote:
Thanks, but it is a little more complicated than that,
the string could be deep in quotes.

The problem is in string substitution.
Suppose I have a dictionary with MY_IP : "172.18.51. 33"

I need to replace all instances of MY_IP with "172.18.51. 33"
in the file.
It is easy in cases such as:
if (MY_IP == "127.0.0.1" ):

But suppose I encounter:"
("(size==23) and (MY_IP==127.0.0 .1)")

In this case I do not want:
("(size==23) and ("172.18.51.33" ==127.0.0.1)")
but:
("(size==23) and (172.18.51.33== 127.0.0.1)")
without the internal quotes.
How can I do this?
I presumed that I would have to check to see if the string
was already in quotes and if so remove the quotes. But not
sure how to do that?
Or is there an easier way?

Thanks in advance:
Michael Yanowitz

-----Original Message-----
From: python-list-bounces+m.yanow itz=kearfott... .@python.org

[mailto:python-list-bounces+m.yanow itz=kearfott... .@python.org]On Behalf
Of half.ital...@gm ail.com
Sent: Wednesday, May 09, 2007 5:12 PM
To: python-l...@python.org
Subject: Re: Checking if string inside quotes?

On May 9, 1:39 pm, "Michael Yanowitz" <m.yanow...@kea rfott.comwrote:
Hello:
If I have a long string (such as a Python file).
I search for a sub-string in that string and find it.
Is there a way to determine if that found sub-string is
inside single-quotes or double-quotes or not inside any quotes?
If so how?
Thanks in advance:
Michael Yanowitz

I think the .find() method returns the index of the found string. You
could check one char before and then one char after the length of the
string to see. I don't use regular expressions much, but I'm sure
that's a more elegant approach.

This will work. You'll get in index error if you find the string at
the very end of the file.

s = """
foo
"bar"
"""
findme = "foo"
index = s.find(findme)

if s[index-1] == "'" and s[index+len(findm e)] == "'":
print "single quoted"
elif s[index-1] == "\"" and s[index+len(findm e)] == "\"":
print "double quoted"
else:
print "unquoted"

~Sean

--http://mail.python.org/mailman/listinfo/python-list
In "nearby" quotes or in quotes at all?
import re
a='abc"def"ghij k'
b=re.sub( r'([\'"])[^\1]*\1', '', a )
b.replace( 'ghi', 'the string' )
#fb: 'abcthe stringjk'
edit()

Here, you get the entire file -in b-, strings omitted entirely, so you
can't write it back.

I've used `tokenize' to parse a file, but you don't get precisely your
original back. Untokenize rearrages your spacings. Equivalent
semantically, so if you want to compile immedately afterwords, you're
alright with that. Short example:
from tokenize import *
import token
from StringIO import StringIO
a= StringIO( 'abc "defghi" ghi jk' )
from collections import deque
b= deque()
for g in generate_tokens ( a.readline ):
if g[0]== token.NAME and g[1]== 'ghi':
b.append( ( token.STRING, '"uchoose"' ) )
else:
b.append( g )

untokenize( b )
#fb: 'abc "defghi""uchoos e"jk '
edit()
acb

May 9 '07 #3
On May 9, 2:31 pm, "Michael Yanowitz" <m.yanow...@kea rfott.comwrote:
Thanks, but it is a little more complicated than that,
the string could be deep in quotes.

The problem is in string substitution.
Suppose I have a dictionary with MY_IP : "172.18.51. 33"

I need to replace all instances of MY_IP with "172.18.51. 33"
in the file.
It is easy in cases such as:
if (MY_IP == "127.0.0.1" ):

But suppose I encounter:"
("(size==23) and (MY_IP==127.0.0 .1)")

In this case I do not want:
("(size==23) and ("172.18.51.33" ==127.0.0.1)")
but:
("(size==23) and (172.18.51.33== 127.0.0.1)")
without the internal quotes.
How can I do this?
I presumed that I would have to check to see if the string
was already in quotes and if so remove the quotes. But not
sure how to do that?
Or is there an easier way?

Thanks in advance:
Michael Yanowitz

-----Original Message-----
From: python-list-bounces+m.yanow itz=kearfott... .@python.org

[mailto:python-list-bounces+m.yanow itz=kearfott... .@python.org]On Behalf
Of half.ital...@gm ail.com
Sent: Wednesday, May 09, 2007 5:12 PM
To: python-l...@python.org
Subject: Re: Checking if string inside quotes?

On May 9, 1:39 pm, "Michael Yanowitz" <m.yanow...@kea rfott.comwrote:
Hello:
If I have a long string (such as a Python file).
I search for a sub-string in that string and find it.
Is there a way to determine if that found sub-string is
inside single-quotes or double-quotes or not inside any quotes?
If so how?
Thanks in advance:
Michael Yanowitz

I think the .find() method returns the index of the found string. You
could check one char before and then one char after the length of the
string to see. I don't use regular expressions much, but I'm sure
that's a more elegant approach.

This will work. You'll get in index error if you find the string at
the very end of the file.

s = """
foo
"bar"
"""
findme = "foo"
index = s.find(findme)

if s[index-1] == "'" and s[index+len(findm e)] == "'":
print "single quoted"
elif s[index-1] == "\"" and s[index+len(findm e)] == "\"":
print "double quoted"
else:
print "unquoted"

~Sean

--http://mail.python.org/mailman/listinfo/python-list
In that case I suppose you'd have to read the file line by line and if
you find your string in the line then search for the indexes of any
matching quotes. If you find matching quotes, see if your word lies
within any of the quote indexes.

#!/usr/bin/env python

file = open("file", 'r')
findme= "foo"
for j, line in enumerate(file) :
found = line.find(findm e)
if found != -1:
quotecount = line.count("'")
quoteindexes = []
start = 0
for i in xrange(quotecou nt):
i = line.find("'", start)
quoteindexes.ap pend(i)
start = i+1

f = False
for i in xrange(len(quot eindexes)/2):
if findme in
line[quoteindexes.po p(0):quoteindex es.pop(0)]:
f = True
print "Found %s on line %s: Single-Quoted" % (findme, j
+1)
if not f:
print "Found %s on line %s: Not quoted" % (findme, j+1)
It's not pretty but it works.

~Sean

May 10 '07 #4
On May 9, 8:48 pm, half.ital...@gm ail.com wrote:
On May 9, 2:31 pm, "Michael Yanowitz" <m.yanow...@kea rfott.comwrote:
Thanks, but it is a little more complicated than that,
the string could be deep in quotes.
The problem is in string substitution.
Suppose I have a dictionary with MY_IP : "172.18.51. 33"
I need to replace all instances of MY_IP with "172.18.51. 33"
in the file.
It is easy in cases such as:
if (MY_IP == "127.0.0.1" ):
But suppose I encounter:"
("(size==23) and (MY_IP==127.0.0 .1)")
In this case I do not want:
("(size==23) and ("172.18.51.33" ==127.0.0.1)")
but:
("(size==23) and (172.18.51.33== 127.0.0.1)")
without the internal quotes.
How can I do this?
I presumed that I would have to check to see if the string
was already in quotes and if so remove the quotes. But not
sure how to do that?
Or is there an easier way?
Thanks in advance:
Michael Yanowitz
-----Original Message-----
From: python-list-bounces+m.yanow itz=kearfott... .@python.org
[mailto:python-list-bounces+m.yanow itz=kearfott... .@python.org]On Behalf
Of half.ital...@gm ail.com
Sent: Wednesday, May 09, 2007 5:12 PM
To: python-l...@python.org
Subject: Re: Checking if string inside quotes?
On May 9, 1:39 pm, "Michael Yanowitz" <m.yanow...@kea rfott.comwrote:
Hello:
If I have a long string (such as a Python file).
I search for a sub-string in that string and find it.
Is there a way to determine if that found sub-string is
inside single-quotes or double-quotes or not inside any quotes?
If so how?
Thanks in advance:
Michael Yanowitz
I think the .find() method returns the index of the found string. You
could check one char before and then one char after the length of the
string to see. I don't use regular expressions much, but I'm sure
that's a more elegant approach.
This will work. You'll get in index error if you find the string at
the very end of the file.
s = """
foo
"bar"
"""
findme = "foo"
index = s.find(findme)
if s[index-1] == "'" and s[index+len(findm e)] == "'":
print "single quoted"
elif s[index-1] == "\"" and s[index+len(findm e)] == "\"":
print "double quoted"
else:
print "unquoted"
~Sean
--http://mail.python.org/mailman/listinfo/python-list

In that case I suppose you'd have to read the file line by line and if
you find your string in the line then search for the indexes of any
matching quotes. If you find matching quotes, see if your word lies
within any of the quote indexes.

#!/usr/bin/env python

file = open("file", 'r')
findme= "foo"
for j, line in enumerate(file) :
found = line.find(findm e)
if found != -1:
quotecount = line.count("'")
quoteindexes = []
start = 0
for i in xrange(quotecou nt):
i = line.find("'", start)
quoteindexes.ap pend(i)
start = i+1

f = False
for i in xrange(len(quot eindexes)/2):
if findme in
line[quoteindexes.po p(0):quoteindex es.pop(0)]:
f = True
print "Found %s on line %s: Single-Quoted" % (findme, j
+1)
if not f:
print "Found %s on line %s: Not quoted" % (findme, j+1)

It's not pretty but it works.

~Sean
This approach omits double-quoted strings, escaped single-quotes "'a
\'b' my tag", triple-quoted strings, as well as multi-line strings of
any type.

Depends what constraints you can sacrifice. Maybe character-at-a-
time, or manually untokenize the solution above. For generic input,
use mine.

May 10 '07 #5

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

Similar topics

5
3750
by: Anders Dalvander | last post by:
os.popen does not work with parameters inside quotes, nor do os.popen. At least on Windows. import os cmd = '"c:\\command.exe" "parameter inside quotes"' os.popen4(cmd) Results in the following error message: 'c:\\command.exe" "parameter inside quotes' is not recognized as an
7
1804
by: RBohannon | last post by:
I'm using A2K. I'm inputing data from a text file into my DB, and I need to check for the data already existing in the DB. If it's already in the DB, I don't want to reenter it. The two tables being used are tblPersonal and tblListData. tblPersonal contains names, SSNs, etc. SSN is the PrimaryKey. tblListData is keyed on the combination of SSN and ExamNum. In tblListData, an SSN can be paired with more than one ExamNum, but the
1
6325
by: Zlatko Matiæ | last post by:
I have a problem when working with PostrgeSQL as back-end. Namely, PostgreSQL syntax uses doble quotes for table names and field names. For example: select = from public."Customers" Therefore, when I write it as a string of a pass-through query or Command Text of ADO Command object it looks like: "select * from public."Customers"" anbd VBA thinks that the first quote after public. is the end of statement. How to solve it ?
5
3242
by: Ann Marinas | last post by:
Happy New Year to all! :D I am currently developoing an application that imports data from a CSV file. Each comma represents an array item that I need to extract data with. My problem is this... I am encountering a string that has the example below: a, b, c. "d,e,f,g", abcdef
12
9637
by: Jeff S | last post by:
In a VB.NET code behind module, I build a string for a link that points to a JavaScript function. The two lines of code below show what is relevant. PopupLink = "javascript:PopUpWindow(" & Chr(34) & PopUpWindowTitle & Chr(34) & ", " & Chr(34) & CurrentEventDetails & ")" strTemp += "<BR><A HREF='#' onClick='" & PopupLink & "'>" & EventName & "</A><BR>" The problem I have is that when the string variables or contain a string with an...
11
3664
by: jarod1701 | last post by:
Hi, i'm currently trying to replace an unknown string using regular expressions. For example I have: user_pref("network.proxy.http", "server1") What do I have to do to replace the "server1" part (which could be
9
7361
by: a | last post by:
I need to write a regular expression to match a quoted string in which the double quote character itself is represented by 2 double quotes. For example: "beginning ""nested quoted string"" end" Any idea how to write this in boost::xpressive or boost::regex. Thanks,
27
10118
by: user | last post by:
Have require file with several query stings in it. Depending on user input one of strings is selected. Everything going along smoothly until I wanted to also input a variable in string. If I put string in program works ok, but, if I use string from require file I can not seem to insert string. $cccb_id is sting..... to be inserted into $query4 and changes depending on user input.
3
1523
by: rajmohan.h | last post by:
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?
0
9257
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...
1
9176
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
8097
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
6702
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
6011
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
4519
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
4784
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2635
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2157
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.