Skip to content

Commit e2cf9a9

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

2 files changed

Lines changed: 16 additions & 3 deletions

File tree

Doc/library/re.rst

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

773773

774-
.. function:: escape(string)
774+
.. function:: escape(pattern)
775775

776-
Escape all the characters in pattern except ASCII letters, numbers and ``'_'``.
776+
Escape all the characters in *pattern* except ASCII letters, numbers and ``'_'``.
777777
This is useful if you want to match an arbitrary literal string that may
778-
have regular expression metacharacters in it.
778+
have regular expression metacharacters in it. For example::
779+
780+
>>> print(re.escape('python.exe'))
781+
python\.exe
782+
783+
>>> legal_chars = string.ascii_lowercase + string.digits + "!#$%&'*+-.^_`|~:"
784+
>>> print('[%s]+' % re.escape(legal_chars))
785+
[abcdefghijklmnopqrstuvwxyz0123456789\!\#\$\%\&\'\*\+\-\.\^_\`\|\~\:]+
786+
787+
>>> operators = ['+', '-', '*', '/', '**']
788+
>>> print('|'.join(map(re.escape, sorted(operators, reverse=True))))
789+
\/|\-|\+|\*\*|\*
779790

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

0 commit comments

Comments
 (0)