newbie question: parse a variable inside an RE?

Vlastimil Brom vlastimil.brom at gmail.com
Mon Dec 1 22:09:33 CET 2008


2008/12/1 <joemacbusiness at gmail.com>

> 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 at dhcppc2 work]$ cat test44.in
> a1
> b1
> g1
> g2
> h1
> h4
> 4g
> 5g
> h5
>
> $ python test45.py
> Selection: g
> you chose  g
> $
>
> Thanks...
> --
> http://mail.python.org/mailman/listinfo/python-list
>
It doesn't seem very robust, but it can be made work, try e.g.:
for item in fname:
  if re.search("^"+newresp, "%s" % (item,)):
  print item,

(prints: g1 g2 in a similar code)
(if you know, that item is a string, the %s interpolation is not needed; you
can also use re match, without hte need for "^" .
hth
  vbr
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20081201/456029b1/attachment.html>


More information about the Python-list mailing list