2012-08-28 44 views

回答

4

确切的翻译是:

node_pattern = re.compile("^\*NODE", re.I) 
element_pattern = re.compile("^\*ELEMENT OUTPUT", re.I) 

if (not re.search(node_pattern, line) or not re.search(element_pattern, line)): 
    print line 

根据你正在尝试做的or在中间可能会更好作为and但我不能s不知道更多关于整个问题。希望这可以帮助!

0

在Python中有更好的方式来做到这一点则正则表达式:

if not line.lower().startswith ('*node') or not line.lower().startswith ('*element output'): 
    print (line) 
0

在我看来,原来的逻辑是错误的。我猜想打算只打印不开始的行或*NODE*ELEMENT OUTPUT(不区分大小写)。但是,任何线条都适用。如果它以*NODE开头,那么它不会以*ELEMENT OUTPUT开头,反之亦然。这样,条件总是评估为True

结论是,即使在原文中,也必须有and而不是or

而且,您必须使用原始的字符串(如r'your pattern'在Python或者你有加倍反引号,我相信,你不希望在正则表达式使用双反斜杠

你可以试试下面的代码片段:。

import re 

simulated_file_content = [ 
    'line 1\n', 
    '*NODE line 2\n', 
    'line 3\n', 
    '*eLeMent Output line 4\n', 
    'line 5\n', 
    ] 


rex = re.compile(r'^\*(NODE)|(ELEMENT OUTPUT)', re.IGNORECASE) 


for line in simulated_file_content: 
    line = line.rstrip() 
    if not rex.search(line): 
     print line 

它显示:

c:\tmp\___python\FaisalSashmi\so12153650>python a.py 
line 1 
line 3 
line 5 
相关问题