【问题标题】:perl regexp curly bracketsperl 正则表达式大括号
【发布时间】:2016-06-11 20:32:48
【问题描述】:

如何匹配 { 和 } 之间的多行。正是我需要匹配下面的块

host customerPERA {
      host-identifier option agent.circuit-id "x:y";
      fixed-address yyy.yyy.yyy.yyy;
      option routers xxx.xxx.xxx.xxx;
      option subnet-mask 255.255.255.0;
}

我必须从非常大的 dhcpd.conf 文件中删除该块。 提前致谢!

附:我忘了,我需要 perl 的正则表达式..

【问题讨论】:

    标签: regex perl


    【解决方案1】:

    我做到了:

    perl  -pe 'BEGIN{undef $/;} s/^host customerPERA[^}]*}//smg' /etc/dhcp/dhcpd.conf 
    

    谢谢大家

    【讨论】:

    • 如果在您的输入中发现任何花括号怎么办?会不会不匹配?
    • @ssr1012:我已经很久没有配置 dhcpd 服务器了,但如果我没记错的话,没有任何实例在主机定义中使用大括号。不过我可能是错的
    【解决方案2】:

    我可以这样做:

    输入:

    host customerPERA{
           host-identifier option agent.circuit-id "x:y";
           fixed-address yyy.yyy.yyy.yyy;
           option routers xxx.xxx.xxx.xxx;
           option subnet-mask 255.255.255.0;
     }
    

    如果是这种情况下找到完全匹配:

    正则表达式模式:

     $myRegex = qw/((?:[^{}]*(?:{(?:[^{}]*(?:{(?:[^{}]*(?:{[^{}]*})*[^{}]*)*})*[^{}]*)*})*[^{}]*)*)/;
    
     if($pattern=~m/host CustomerPERA\{$myRegex\}/gs)
     {
          #do it you statement here
     }
    

    【讨论】:

      【解决方案3】:

      您的问题的解决方案:

      perl -p0i -e 's/host\s+customerPERA\s+\{[^}]+\}/host customerPERA {}/g' /etc/dhcp/dhcpd.conf
      

      它将替换“host customerPERA {}”上的“host customerPERA {}”(带空大括号)

      【讨论】:

      • 可能还需要 /s 多行
      • @xxfelixxx: /s 改变了. 的行为方式。正则表达式中没有.
      • /m 改变了 ^$ 的行为方式。这里不需要。
      • 我正在尝试使用以下命令删除该块: perl -pi -e "s/^host customerPERA \{[^}]*\}//" /etc/dhcp/dhcpd.conf without成功
      • perl -e 'open my $fh, "/etc/dhcp/dhcpd.conf" or die "Unable to open : $!";我的 $txt = 做 { 本地 $/; }; $txt =~ s/host\s+customerPERA\s+\{([^}]+)\}//m;打印 $txt;'
      【解决方案4】:

      您可能希望在本地使用 single line modifier(?s)。 这可以为您提供一行代码来删除或编辑您想要的内容。

      $string =~ s/host customerPERA \{(?s).+?\}//;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-10-18
        • 1970-01-01
        • 2013-05-02
        • 2018-08-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多