regexp questoin

micklee74 at hotmail.com micklee74 at hotmail.com
Fri Jun 9 20:44:42 EDT 2006


Fredrik Lundh wrote:
> 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>


hi. thanks for all the help.
actually, i am doing an application that allows user to delete files by
entering an input pattern. so if he has files that have special
characters such as [-] or others, then i want to filter them off ....
the solution for re.compile(re.escape(userinput)) might work, i have to
give it a try.
thanks again.




More information about the Python-list mailing list