我在python中有以下代码段
import re
lines = "#define __xyz_pqr_tqe_ope_H__"
re.sub('(__)([a-zA-Z0-9_]+)(__)', '\1ab\2\3null', lines)
print(lines)
仅当看到#define或#undef
时,我才想使用正则表达式用空白替换开头和结尾的双下划线/单下划线(如果可能)这意味着我的输出应类似于
#define xyz_pqr_tqe_ope_H
答案 0 :(得分:2)
import re
lines = "#define __T194_MTS_MB1_PROTOCOL_H__"
lines = re.sub(r'( _{1,2})|(_{1,2}$)', ' ', lines)
print(lines)
并且 re 不会就地修改字符串,您应该将其返回。
答案 1 :(得分:1)
使用str.strip
例如:
lines = "#define __T194_MTS_MB1_PROTOCOL_H__"
print( " ".join(i.strip("_") for i in lines.split()) )
输出:
#define T194_MTS_MB1_PROTOCOL_H
答案 2 :(得分:1)
答案 3 :(得分:1)
我在这里固定了一些零件:
import re
lines = "#define __T194_MTS_MB1_PROTOCOL_H__"
lines = re.sub('(#define|#undef)(\s+)__?(.+[^_])__?(\s+|$)',
r'\1\2\3\4', lines)
print(lines)
re.sub
返回修改后的字符串\\
)。在此,这对'\1\2\3'
特别有用,它们不会被处理为特殊字符__?
前的最后一个字符不能为_
结果,用于所有带有预处理器命令的双/单个下划线强调组合 ,#undef
和#define
,以及< strong> typos ,以表明在以下情况下它不会替代:
#undef __T194_MTS_MB1_PROTOCOL_H__: #undef T194_MTS_MB1_PROTOCOL_H
#undef _T194_MTS_MB1_PROTOCOL_H_: #undef T194_MTS_MB1_PROTOCOL_H
#undef _T194_MTS_MB1_PROTOCOL_H__: #undef T194_MTS_MB1_PROTOCOL_H
#undef __T194_MTS_MB1_PROTOCOL_H_: #undef T194_MTS_MB1_PROTOCOL_H
#define __T194_MTS_MB1_PROTOCOL_H__: #define T194_MTS_MB1_PROTOCOL_H
#define _T194_MTS_MB1_PROTOCOL_H_: #define T194_MTS_MB1_PROTOCOL_H
#define _T194_MTS_MB1_PROTOCOL_H__: #define T194_MTS_MB1_PROTOCOL_H
#define __T194_MTS_MB1_PROTOCOL_H_: #define T194_MTS_MB1_PROTOCOL_H
#undeef __T194_MTS_MB1_PROTOCOL_H__: #undeef __T194_MTS_MB1_PROTOCOL_H__
#undeef _T194_MTS_MB1_PROTOCOL_H_: #undeef _T194_MTS_MB1_PROTOCOL_H_
#undeef _T194_MTS_MB1_PROTOCOL_H__: #undeef _T194_MTS_MB1_PROTOCOL_H__
#undeef __T194_MTS_MB1_PROTOCOL_H_: #undeef __T194_MTS_MB1_PROTOCOL_H_
#deefine __T194_MTS_MB1_PROTOCOL_H__: #deefine __T194_MTS_MB1_PROTOCOL_H__
#deefine _T194_MTS_MB1_PROTOCOL_H_: #deefine _T194_MTS_MB1_PROTOCOL_H_
#deefine _T194_MTS_MB1_PROTOCOL_H__: #deefine _T194_MTS_MB1_PROTOCOL_H__
#deefine __T194_MTS_MB1_PROTOCOL_H_: #deefine __T194_MTS_MB1_PROTOCOL_H_