Index: Lib/re.py =================================================================== --- Lib/re.py (revision 62469) +++ Lib/re.py (working copy) @@ -196,22 +196,18 @@ "Compile a template pattern, returning a pattern object" return _compile(pattern, flags|T) -_alphanum = {} -for c in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890': - _alphanum[c] = 1 -del c +_special = {} +for c in '.^$*+?{}[]\\|()': + _special[c] = 1 def escape(pattern): - "Escape all non-alphanumeric characters in pattern." + "Escape all special characters in pattern." s = list(pattern) - alphanum = _alphanum + special = _special for i in range(len(pattern)): c = pattern[i] - if c not in alphanum: - if c == "\000": - s[i] = "\\000" - else: - s[i] = "\\" + c + if c in special: + s[i] = "\\" + c return pattern[:0].join(s) # -------------------------------------------------------------------- Index: Lib/test/test_re.py =================================================================== --- Lib/test/test_re.py (revision 62469) +++ Lib/test/test_re.py (working copy) @@ -441,6 +441,12 @@ pat=re.compile(re.escape(p)) self.assertEqual(pat.match(p) is not None, True) self.assertEqual(pat.match(p).span(), (0,256)) + + # letters, digits, and _ should be left alone + same = "abcdefghijklmnopqrstuvwxyz" + \ + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + \ + "0123456789_" + self.assertEqual(re.escape(same), same) def test_pickling(self): import pickle