diff options
author | Serhiy Storchaka <storchaka@gmail.com> | 2017-04-13 16:41:26 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2017-04-13 16:41:26 (GMT) |
commit | e2cf9a918439006fb27f67c1939d0370886650e7 (patch) | |
tree | 6a1ecef63613593a09eddb37ad8d5131d645593f /Doc/library | |
parent | df9783720e40773e7854d2f4e4cfc93f0a2c08b8 (diff) | |
download | cpython-e2cf9a918439006fb27f67c1939d0370886650e7.zip cpython-e2cf9a918439006fb27f67c1939d0370886650e7.tar.gz cpython-e2cf9a918439006fb27f67c1939d0370886650e7.tar.bz2 |
bpo-30021: Add examples for re.escape(). (#1048) (#1116)
And fix the parameter name.
(cherry picked from commit 8fc7bc2b7631ee819ee614e47b6f44bacebe1574)
Diffstat (limited to 'Doc/library')
-rw-r--r-- | Doc/library/re.rst | 17 |
1 files changed, 14 insertions, 3 deletions
diff --git a/Doc/library/re.rst b/Doc/library/re.rst index 6baac6f..d33fff8 100644 --- a/Doc/library/re.rst +++ b/Doc/library/re.rst @@ -771,11 +771,22 @@ form. Unmatched groups are replaced with an empty string. -.. function:: escape(string) +.. function:: escape(pattern) - Escape all the characters in pattern except ASCII letters, numbers and ``'_'``. + Escape all the characters in *pattern* except ASCII letters, numbers and ``'_'``. This is useful if you want to match an arbitrary literal string that may - have regular expression metacharacters in it. + have regular expression metacharacters in it. For example:: + + >>> print(re.escape('python.exe')) + python\.exe + + >>> legal_chars = string.ascii_lowercase + string.digits + "!#$%&'*+-.^_`|~:" + >>> print('[%s]+' % re.escape(legal_chars)) + [abcdefghijklmnopqrstuvwxyz0123456789\!\#\$\%\&\'\*\+\-\.\^_\`\|\~\:]+ + + >>> operators = ['+', '-', '*', '/', '**'] + >>> print('|'.join(map(re.escape, sorted(operators, reverse=True)))) + \/|\-|\+|\*\*|\* .. versionchanged:: 3.3 The ``'_'`` character is no longer escaped. |