Skip to content

Commit 01d3afe

Browse files
authored
Merge pull request yidao620c#303 from ronghuaxueleng/master
第二章第五节搜索和替换中补充命名分组的替换写法
2 parents b4416ae + 33594bf commit 01d3afe

File tree

2 files changed

+11
-0
lines changed

2 files changed

+11
-0
lines changed

cookbook/c02/p05_search_replace.py

+1
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ def search_replace():
2020
# 复杂的模式,使用sub()
2121
text = 'Today is 11/27/2012. PyCon starts 3/13/2013.'
2222
print(re.sub(r'(\d+)/(\d+)/(\d+)', r'\3-\1-\2', text))
23+
print(re.sub(r'(?P<month>\d+)/(?P<day>\d+)/(?P<year>\d+)', r'\g<year>-\g<month>-\g<day>', text))
2324

2425
# 先编译
2526
datepat = re.compile(r'(\d+)/(\d+)/(\d+)')

source/c02/p05_search_and_replace_text.rst

+10
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,16 @@
4242
'Today is 2012-11-27. PyCon starts 2013-3-13.'
4343
>>>
4444
45+
如果你使用了命名分组,那么第二个参数请使用 ``\g<group_name>`` ,如下
46+
47+
.. code-block:: python
48+
49+
>>> text = 'Today is 11/27/2012. PyCon starts 3/13/2013.'
50+
>>> import re
51+
>>> re.sub(r'(?P<month>\d+)/(?P<day>\d+)/(?P<year>\d+)', r'\g<year>-\g<month>-\g<day>', text)
52+
'Today is 2012-11-27. PyCon starts 2013-3-13.'
53+
>>>
54+
4555
对于更加复杂的替换,可以传递一个替换回调函数来代替,比如:
4656

4757
.. code-block:: python

0 commit comments

Comments
 (0)