【问题标题】:how to convert perl regex to python?如何将 perl 正则表达式转换为 python?
【发布时间】:2012-08-28 06:12:14
【问题描述】:

我正在尝试将此正则表达式从 Perl 转换为 Python:

if ($line !~ /^\*NODE/i || $line !~ /^\*ELEMENT OUTPUT/i)
{
    print $line;
}

我已经编写了这段 Python 代码,但它失败了:

if (re.search("^!\*ELEMENT OUTPUT | ^!\*NODE", line)):
   print line

【问题讨论】:

    标签: python regex perl python-3.x


    【解决方案1】:

    准确的翻译是:

    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 更好,但如果不了解整个问题,我无法确定。希望这会有所帮助!

    【讨论】:

      【解决方案2】:

      在 python 中,有比正则表达式更好的方法:

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

      【讨论】:

        【解决方案3】:

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

        结论,原版中一定有and而不是or

        此外,您必须使用原始字符串(例如 Python 中的r'your pattern',否则您必须加倍反斜杠。我相信,您不想在正则表达式中加倍反斜杠。

        你可以试试下面的sn-p:

        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
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-01-02
          • 1970-01-01
          • 2023-03-14
          • 1970-01-01
          • 1970-01-01
          • 2015-09-26
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多