2013-01-21 134 views
0
REGEXES = [(re.compile(r'cat'), 'cat2'), 
      (re.compile(r'(if)(.*)(\r?\n)(\s*)(logger.info)(.*)'), '\1\2')] 

for search, replace in REGEXES: 
        line = search.sub(replace, line) 

为什么不工作就可以了...Python的正则表达式不工作

if(List != null) { 
    logger.info("List is not null"); 
    fieldSetContainerList.clear(); 
} 

做工精细,用记事本++正则表达式搜索替换。 用法:要删除所有if语句下面的logger.info语句。

+1

像@NPE说:它应该工作使用'R '\ 1 \ 2')]',而不是''\ 1 \ 2')]' – lv10

回答

1

您需要使用原始字符串:

 (re.compile(r'(if)(.*)(\r?\n)(\s*)(logger.info)(.*)'), r'\1\2')] 
                  ^here 

用此修复程序,您正则表达式为我工作。没有它,\1\2会在解析字符串文字时处理,并且永远不会将其输入到正则表达式引擎。

这里是我的测试代码:

import re 

line = """if(List != null) { 
    logger.info("List is not null"); 
    fieldSetContainerList.clear(); 
} 
""" 

REGEXES = [(re.compile(r'cat'), 'cat2'), 
      (re.compile(r'(if)(.*)(\r?\n)(\s*)(logger.info)(.*)'), r'\1\2')] 

for search, replace in REGEXES: 
    line = search.sub(replace, line) 
print line 

运行时,该打印

if(List != null) { 
    fieldSetContainerList.clear(); 
} 
+0

不知道为什么它不适合我。请参阅[链接](http://stackoverflow.com/a/14445401/1278540)。 –