bpo-30021: Add examples for re.escape(). (#1048) (#1116)

And fix the parameter name.

(cherry picked from commit 8fc7bc2b76)
This commit is contained in:
Serhiy Storchaka 2017-04-13 19:41:26 +03:00 committed by GitHub
parent df9783720e
commit e2cf9a9184
2 changed files with 16 additions and 3 deletions

View file

@ -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.

View file

@ -274,6 +274,8 @@ whatsnew/3.2,,:location,zope9-location = ${zope9:location}
whatsnew/3.2,,:prefix,zope-conf = ${custom:prefix}/etc/zope.conf
whatsnew/changelog,,:gz,": TarFile opened with external fileobj and ""w:gz"" mode didn't"
whatsnew/changelog,,::,": Use ""127.0.0.1"" or ""::1"" instead of ""localhost"" as much as"
library/re,,`,!#$%&'*+-.^_`|~:
library/re,,`,\!\#\$\%\&\'\*\+\-\.\^_\`\|\~\:
library/tarfile,149,:xz,'x:xz'
library/xml.etree.elementtree,290,:sometag,prefix:sometag
library/xml.etree.elementtree,301,:fictional,"<actors xmlns:fictional=""http://characters.example.com"""

1 c-api/arg :ref PyArg_ParseTuple(args, "O|O:ref", &object, &callback)
274 whatsnew/3.2 :prefix zope-conf = ${custom:prefix}/etc/zope.conf
275 whatsnew/changelog :gz : TarFile opened with external fileobj and "w:gz" mode didn't
276 whatsnew/changelog :: : Use "127.0.0.1" or "::1" instead of "localhost" as much as
277 library/re ` !#$%&'*+-.^_`|~:
278 library/re ` \!\#\$\%\&\'\*\+\-\.\^_\`\|\~\:
279 library/tarfile 149 :xz 'x:xz'
280 library/xml.etree.elementtree 290 :sometag prefix:sometag
281 library/xml.etree.elementtree 301 :fictional <actors xmlns:fictional="http://characters.example.com"