From 3ff262e08f2025f3c579ebf107f8aec7f9ac353d Mon Sep 17 00:00:00 2001 From: Paul Sokolovsky Date: Fri, 9 May 2014 23:07:29 +0300 Subject: [PATCH] re-pcre: Add escape() function. --- re-pcre/re.py | 10 ++++++++++ re-pcre/test_re.py | 2 ++ 2 files changed, 12 insertions(+) diff --git a/re-pcre/re.py b/re-pcre/re.py index 10faa43f..88abcfc1 100644 --- a/re-pcre/re.py +++ b/re-pcre/re.py @@ -116,3 +116,13 @@ def match(pattern, string, flags=0): def sub(pattern, repl, s, count=0, flags=0): r = compile(pattern, flags) return r.sub(repl, s) + + +def escape(s): + res = "" + for c in s: + if '0' <= c <= '9' or 'A' <= c <= 'Z' or 'a' <= c <= 'z' or c == '_': + res += c + else: + res += "\\" + c + return res diff --git a/re-pcre/test_re.py b/re-pcre/test_re.py index 5ac42fd8..a026f76a 100644 --- a/re-pcre/test_re.py +++ b/re-pcre/test_re.py @@ -14,3 +14,5 @@ assert re.sub("a", lambda m: m.group(0) * 2, "caaab") == "caaaaaab" m = re.match(r"(\d+)\.(\d+)", "24.1632") assert m.groups() == ('24', '1632') + +assert re.escape(r"1243*&[]_dsfAd") == r"1243\*\&\[\]_dsfAd"