2008/12/1 <[EMAIL PROTECTED]> > 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, > > [EMAIL PROTECTED] 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
-- http://mail.python.org/mailman/listinfo/python-list