Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #93743
| Date | 2015-07-12 20:25 +0100 |
|---|---|
| From | MRAB <python@mrabarnett.plus.com> |
| Subject | Re: Python backreference replacing doesn't work as expected |
| References | <a88a0c98-aa8d-4b10-8162-acfb81933695@googlegroups.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.455.1436729160.3674.python-list@python.org> (permalink) |
On 2015-07-12 10:40, Yonggang Chen wrote:
> There are two named groups in my pattern: myFlag and id, I want to add one more myFlag immediately before group id.
>
> Here is my current code:
> ## code begin
> # i'm using Python 3.4.2
> import re
> import os
> contents = b'''
> xdlg::xdlg(x_app* pApp, CWnd* pParent)
> : customized_dlg((UINT)0, pParent, pApp)
> , m_pReaderApp(pApp)
> , m_info(pApp)
> {
>
> }
> '''
>
> pattern = rb'(?P<myFlag>[a-zA-Z0-9_]+)::(?P=myFlag).+:.+(?P<id>\(UINT\)0 *,)'
> res = re.search(pattern, contents, re.DOTALL)
> if None != res:
> print(res.groups()) # the output is (b'xdlg', b'(UINT)0,')
>
> # 'replPattern' becomes b'(?P<myFlag>[a-zA-Z0-9_]+)::(?P=myFlag).+:.+((?P=myFlag)\\(UINT\\)0 *,)'
In a replacement template, the (?P...) parts are just literals.
> replPattern = pattern.replace(b'?P<id>', b'(?P=myFlag)', re.DOTALL)
This .replace method is a string method. It has nothing to do with
regex.
> print(replPattern)
> contents = re.sub(pattern, replPattern, contents)
You're not passing in the DOTALL flag; this function doesn't have an
argument for the flags, anyway.
You could compile the regex and then use its .sub method, or use inline
flags instead.
> print(contents)
> # code end
>
> The expected results should be:
>
> xdlg::xdlg(x_app* pApp, CWnd* pParent)
> : customized_dlg(xdlg(UINT)0, pParent, pApp)
> , m_pReaderApp(pApp)
> , m_info(pApp)
> {
>
> }
>
> but now the result this the same with the original:
>
> xdlg::xdlg(x_app* pApp, CWnd* pParent)
> : customized_dlg((UINT)0, pParent, pApp)
> , m_pReaderApp(pApp)
> , m_info(pApp)
> {
>
> }
>
Back to comp.lang.python | Previous | Next — Previous in thread | Find similar | Unroll thread
Python backreference replacing doesn't work as expected Yonggang Chen <yonggangchen168@gmail.com> - 2015-07-12 02:40 -0700 Re: Python backreference replacing doesn't work as expected MRAB <python@mrabarnett.plus.com> - 2015-07-12 20:25 +0100
csiph-web