2013-01-21 139 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)。 –