Skip to content

Commit 9366332

Browse files
bpo-30021: Add examples for re.escape(). (#1048) (#1115)
And fix the parameter name. (cherry picked from commit 8fc7bc2)
1 parent 119d94a commit 9366332

File tree

2 files changed

+16
-3
lines changed

2 files changed

+16
-3
lines changed

Doc/library/re.rst

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -784,11 +784,22 @@ form.
784784
Unmatched groups are replaced with an empty string.
785785

786786

787-
.. function:: escape(string)
787+
.. function:: escape(pattern)
788788

789-
Escape all the characters in pattern except ASCII letters, numbers and ``'_'``.
789+
Escape all the characters in *pattern* except ASCII letters, numbers and ``'_'``.
790790
This is useful if you want to match an arbitrary literal string that may
791-
have regular expression metacharacters in it.
791+
have regular expression metacharacters in it. For example::
792+
793+
>>> print(re.escape('python.exe'))
794+
python\.exe
795+
796+
>>> legal_chars = string.ascii_lowercase + string.digits + "!#$%&'*+-.^_`|~:"
797+
>>> print('[%s]+' % re.escape(legal_chars))
798+
[abcdefghijklmnopqrstuvwxyz0123456789\!\#\$\%\&\'\*\+\-\.\^_\`\|\~\:]+
799+
800+
>>> operators = ['+', '-', '*', '/', '**']
801+
>>> print('|'.join(map(re.escape, sorted(operators, reverse=True))))
802+
\/|\-|\+|\*\*|\*
792803

793804
.. versionchanged:: 3.3
794805
The ``'_'`` character is no longer escaped.

Doc/tools/susp-ignored.csv

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -302,6 +302,8 @@ whatsnew/3.2,,:feed,>>> urllib.parse.urlparse('http://[dead:beef:cafe:5417:affe:
302302
whatsnew/3.2,,:gz,">>> with tarfile.open(name='myarchive.tar.gz', mode='w:gz') as tf:"
303303
whatsnew/3.2,,:location,zope9-location = ${zope9:location}
304304
whatsnew/3.2,,:prefix,zope-conf = ${custom:prefix}/etc/zope.conf
305+
library/re,,`,!#$%&'*+-.^_`|~:
306+
library/re,,`,\!\#\$\%\&\'\*\+\-\.\^_\`\|\~\:
305307
library/tarfile,,:xz,'x:xz'
306308
library/xml.etree.elementtree,,:sometag,prefix:sometag
307309
library/xml.etree.elementtree,,:fictional,"<actors xmlns:fictional=""http://characters.example.com"""

0 commit comments

Comments
 (0)