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"