我想这正则表达式在Perl转换到Python:如何将perl正则表达式转换为python?
if ($line !~ /^\*NODE/i || $line !~ /^\*ELEMENT OUTPUT/i)
{
print $line;
}
我写了这Python代码,但它失败:
if (re.search("^!\*ELEMENT OUTPUT | ^!\*NODE", line)):
print line
我想这正则表达式在Perl转换到Python:如何将perl正则表达式转换为python?
if ($line !~ /^\*NODE/i || $line !~ /^\*ELEMENT OUTPUT/i)
{
print $line;
}
我写了这Python代码,但它失败:
if (re.search("^!\*ELEMENT OUTPUT | ^!\*NODE", line)):
print line
确切的翻译是:
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不知道更多关于整个问题。希望这可以帮助!
在Python中有更好的方式来做到这一点则正则表达式:
if not line.lower().startswith ('*node') or not line.lower().startswith ('*element output'):
print (line)
在我看来,原来的逻辑是错误的。我猜想打算只打印不开始的行或*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