regexp questoin

Fredrik Lundh fredrik at pythonware.com
Fri Jun 9 15:50:56 EDT 2006


micklee74 at hotmail.com wrote:

 > pat = re.compile(r"%s" %(userinput) )  #userinput is passed from
 > command line argument

that r"%s" % (userinput) thing is a pointless operation: the "r" prefix 
controls how backslashes in a string literal is parsed; the result is an 
ordinary string ("%s" in this case).

in other words,

    pat = re.compile(r"%s" % (userinput))

is just a slightly convoluted way to write

    pat = re.compile(str(userinput))

and since you know that userinput is a string (at least if you got it 
from sys.argv), you might as well write

    pat = re.compile(userinput)

> if the user key in a pattern , eg [-] ,  and my script will search some
> lines that contains [-]
> 
> pat.findall(lines)
> 
> but the script produce some error: sre_constants.error: unexpected end
> of regular expression

for what pattern?  "[-]" is a valid regular expression (it matches a 
single minus), but e.g. "[-" is invalid.  to deal with this, catch the
exception:

    try:
       pat = re.compile(userinput)
    except re.error:
       print "invalid regular expression:", userinput
       sys.exit()

hope this helps!

</F>




More information about the Python-list mailing list