Perl 和 Regex - 单行模式匹配

Perl and Regex - single line mode matching

为什么

perl -ne "print if /(<Conn)([\S|\s]+?)(>)/sg;" /path/to/file

匹配

<Connector port="PORT" protocol="HTTP/1.1" SSLEnabled="true"
           maxThreads="150" scheme="https" secure="true"
           clientAuth="false" sslProtocol="TLS" />`

当它匹配时

<Connector port="PORT" protocol="AJP/1.3" redirectPort="PORT" />

我需要做什么才能用相同的正则表达式匹配两者?

因为它是运行 line-wise。在您的第一个数据上,$_ 将采用三个独立的值

  1. <Connector port="PORT" protocol="HTTP/1.1" SSLEnabled="true"
    
  2. maxThreads="150" scheme="https" secure="true"
    
  3. clientAuth="false" sslProtocol="TLS" />
    
其中

和 none 将自行匹配。

如果你想让它匹配,也许你可以尝试 slurping 整个文件。

my $whole_file = do { local $/; <> };

-n 选项逐行读取文件,但您可以通过取消定义输入行终止符来更改整个文件的行。这是使用 local $/; 或使用命令行选项 -0777 完成的,如下所示:

perl -0777ne 'print "\n" while /(<Conn.+?>)/sg;' /path/to/file

一次读入整个文件。如果这是一个问题,请尝试在命令行上将 $/ 设置为 >(因为您的模式总是以 > 结尾)或 -o076

perl -076ne 'print "\n" if /(<Conn.+?>)/sg;' /path/to/file