From 068dc1571903b0fed18f13ed7e65235b998f1f70 Mon Sep 17 00:00:00 2001 From: chang-ning Date: Fri, 4 Mar 2016 00:35:14 +0800 Subject: [PATCH] Add some regular notes --- docs/notes/python-rexp.rst | 55 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/docs/notes/python-rexp.rst b/docs/notes/python-rexp.rst index 2f9b913e..6c978fdd 100644 --- a/docs/notes/python-rexp.rst +++ b/docs/notes/python-rexp.rst @@ -138,3 +138,58 @@ Named Grouping ``(?P)`` # back reference ``(?P=name)`` >>> re.search('^(?P[a-z])(?P=char)','aa') <_sre.SRE_Match object at 0x10ae0f288> + + +Substitute String +----------------- + +.. code-block:: python + + # basic substitute + >>> res = "1a2b3c" + >>> re.sub(r'[a-z]',' ', res) + '1 2 3 ' + + # substitute with group reference + >>> date = r'2016-01-01' + >>> re.sub(r'(\d{4})-(\d{2})-(\d{2})',r'\2/\3/\1/',date) + '01/01/2016/' + + # camelcase to underscore + >>> def convert(s): + ... res = re.sub(r'(.)([A-Z][a-z]+)',r'\1_\2', s) + ... return re.sub(r'([a-z])([A-Z])',r'\1_\2', res).lower() + ... + >>> convert('CamelCase') + 'camel_case' + >>> convert('CamelCamelCase') + 'camel_camel_case' + >>> convert('SimpleHTTPServer') + 'simple_http_server' + +Look around +----------- + ++---------------+---------------------+ +| notation | compare direction | ++===============+=====================+ +| ``(?=...)`` | left to right | ++---------------+---------------------+ +| ``(?!...)`` | left to right | ++---------------+---------------------+ +| ``(?<=...)`` | right to left | ++---------------+---------------------+ +| ``(?!<...)`` | right to left | ++---------------+---------------------+ + +.. code-block:: python + + # basic + >>> re.sub('(?=\d{3})', ' ', '12345') + ' 1 2 345' + >>> re.sub('(?!\d{3})', ' ', '12345') + '123 4 5 ' + >>> re.sub('(?<=\d{3})', ' ', '12345') + '123 4 5 ' + >>> re.sub('(?