[Tutor] How to use variables in regular expressions?

Scott Moynes smoynes@nexus.carleton.ca
Tue, 6 Nov 2001 20:50:37 -0500


--SLDf9lqlvOQaIe6s
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

* HY (pythonpython@hotmail.com) wrote:
> I understand that ( ) [ ] are special symbols used by Python,
> but is there a good way to solve this problem?

I think it has more to do with the fact that they are special regexp
symbols, but fortunately there is a good (and simple) way to solve
this problem.

re.escape(string) "Returns string with all non-alphanumerics
backslashed; this is useful if you want to match an arbitrary literal
string that may have regular expression metacharacters in it."

So, your code would become:=20

>>> x=3D"(a)[b]c"
>>> re.search( re.escape(x)+"def", "(a)[b]cdefg")
<SRE_Match object at 0x8059810>

hth

scott
--
Copyleft (c) 2001, Scott Moynes
--SLDf9lqlvOQaIe6s
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAjvok20ACgkQiPjBXy2RebBipQCfRafwU09wh112WY4mwz52mYvS
bBoAn0dtW6Hs6EqDYkd4uc4xaTO051Jg
=N3KN
-----END PGP SIGNATURE-----

--SLDf9lqlvOQaIe6s--