Python feedback replacement not working as expected

There are two named groups in my template: myFlag and id , I want to add another myFlag just before the group id .

Here is my current code:

# 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 *,)'
replPattern = pattern.replace(b'?P<id>', b'(?P=myFlag)', re.DOTALL)
print(replPattern)
contents = re.sub(pattern, replPattern, contents)
print(contents)

      

Expected results:

xdlg::xdlg(x_app* pApp, CWnd* pParent)
    : customized_dlg(xdlg(UINT)0, pParent, pApp)
    , m_pReaderApp(pApp)
    , m_info(pApp)
{

}

      

but now the result is the same as the original:

 xdlg::xdlg(x_app* pApp, CWnd* pParent)
    : customized_dlg((UINT)0, pParent, pApp)
    , m_pReaderApp(pApp)
    , m_info(pApp)
{

}

      

+3


source to share


1 answer


The problem lies in the syntax of the template - especially at the end:

0 *,)

It doesn't make any sense ... the fix seems to solve most of the problems, although I would recommend deflating DOTALL

and instead MULTILINE

:

p = re.compile(ur'([a-zA-Z0-9_]+)::\1(.*\n\W+:.*)(\(UINT\)0,.*)', re.MULTILINE)
sub = u"\\1::\\1\\2\\1\\3"
result = re.sub(p, sub, s)

print(result)

      



Result:

xdlg::xdlg(x_app* pApp, CWnd* pParent)
    : customized_dlg(xdlg(UINT)0, pParent, pApp)
    , m_pReaderApp(pApp)
    , m_info(pApp)
{

}

      

https://regex101.com/r/hG3lV7/1

+2


source







All Articles