newbie question: parse a variable inside an RE?

J

joemacbusiness

Hi All,

How do I parse a variable inside an RE?
What is the re.search() syntax when your
search string is a variable?
It's easy to parse hardcoded RE's but not
if you use a variable.

Here is my code, input and runtime:

$ cat test45.py
#!/usr/bin/python

import re

resp = raw_input('Selection: ')
newresp = resp.strip()
print "you chose ", newresp

fname = open('test44.in')
for I in fname:
# if re.search('^newresp', "%s"%(I)): # returns nothing
# if re.search(^newresp, "%s"%(I)): # syntax error
if re.search("^newresp", "%s"%(I)): # returns nothing
print I,

[jmccaughan@dhcppc2 work]$ cat test44.in
a1
b1
g1
g2
h1
h4
4g
5g
h5

$ python test45.py
Selection: g
you chose g
$

Thanks...
 
D

Diez B. Roggisch

Hi All,

How do I parse a variable inside an RE?
What is the re.search() syntax when your
search string is a variable?
It's easy to parse hardcoded RE's but not
if you use a variable.

Both are exactly equal in difficulty.
Here is my code, input and runtime:

$ cat test45.py
#!/usr/bin/python

import re

resp = raw_input('Selection: ')
newresp = resp.strip()
print "you chose ", newresp

fname = open('test44.in')
for I in fname:
# if re.search('^newresp', "%s"%(I)): # returns nothing
# if re.search(^newresp, "%s"%(I)): # syntax error
if re.search("^newresp", "%s"%(I)): # returns nothing
print I,

How should python know that you want the newresp being expanded? And not
that you want to search for the word "newresp"?


You need to use the *variable* newresp:

if re.search(newresp, I): ...

If you want to alter it to have a "^" prepended before you use it, you
need to do so:

newresp = "^" + newresp

And as show above,

"%s" % I

is nothing but I - no need for the string-interpolation.

Diez
 
J

John Machin

Both are exactly equal in difficulty.










How should python know that you want the newresp being expanded? And not
that you want to search for the word "newresp"?

You need to use the *variable* newresp:

if re.search(newresp, I): ...

If you want to alter it to have a "^" prepended before you use it, you
need to do so:

newresp = "^" + newresp

And as show above,

"%s" % I

is nothing but I - no need for the string-interpolation.

In fact what the OP is trying to do amounts to a convoluted version of
I.startswith(newresp) which probably isn't his real requirement
anyway :-(
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,535
Members
45,007
Latest member
obedient dusk

Latest Threads

Top