From 33594bffa5ccc6e6524ea0e9da7900c00b1c0d06 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9B=B9=E5=BC=BA?= Date: Sun, 20 Oct 2019 20:56:22 +0800 Subject: [PATCH] =?UTF-8?q?=E7=AC=AC=E4=BA=8C=E7=AB=A0=E7=AC=AC=E4=BA=94?= =?UTF-8?q?=E8=8A=82=E6=90=9C=E7=B4=A2=E5=92=8C=E6=9B=BF=E6=8D=A2=E4=B8=AD?= =?UTF-8?q?=E8=A1=A5=E5=85=85=E5=91=BD=E5=90=8D=E5=88=86=E7=BB=84=E7=9A=84?= =?UTF-8?q?=E6=9B=BF=E6=8D=A2=E5=86=99=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cookbook/c02/p05_search_replace.py | 1 + source/c02/p05_search_and_replace_text.rst | 10 ++++++++++ 2 files changed, 11 insertions(+) diff --git a/cookbook/c02/p05_search_replace.py b/cookbook/c02/p05_search_replace.py index 4111f24..81aeaa1 100644 --- a/cookbook/c02/p05_search_replace.py +++ b/cookbook/c02/p05_search_replace.py @@ -20,6 +20,7 @@ def search_replace(): # 复杂的模式,使用sub() text = 'Today is 11/27/2012. PyCon starts 3/13/2013.' print(re.sub(r'(\d+)/(\d+)/(\d+)', r'\3-\1-\2', text)) + print(re.sub(r'(?P\d+)/(?P\d+)/(?P\d+)', r'\g-\g-\g', text)) # 先编译 datepat = re.compile(r'(\d+)/(\d+)/(\d+)') diff --git a/source/c02/p05_search_and_replace_text.rst b/source/c02/p05_search_and_replace_text.rst index b301f04..73cb589 100644 --- a/source/c02/p05_search_and_replace_text.rst +++ b/source/c02/p05_search_and_replace_text.rst @@ -42,6 +42,16 @@ 'Today is 2012-11-27. PyCon starts 2013-3-13.' >>> +如果你使用了命名分组,那么第二个参数请使用 ``\g`` ,如下 + +.. code-block:: python + + >>> text = 'Today is 11/27/2012. PyCon starts 3/13/2013.' + >>> import re + >>> re.sub(r'(?P\d+)/(?P\d+)/(?P\d+)', r'\g-\g-\g', text) + 'Today is 2012-11-27. PyCon starts 2013-3-13.' + >>> + 对于更加复杂的替换,可以传递一个替换回调函数来代替,比如: .. code-block:: python