【问题标题】:Perl \R regex strip Windows newline characterPerl \R 正则表达式去除 Windows 换行符
【发布时间】:2015-08-19 06:15:44
【问题描述】:

我正在使用 Perl 脚本,使用以下代码删除输入文件中可能的 Windows 换行符:

foreach my $line(split /\r|\R/)

在两台不同的 Linux 机器上执行相同的脚本会产生不同的结果。在 machine1 上,脚本按预期工作,在 machine2 上,每次找到大写“R”字符时,都会拆分行并导致结果混乱。

我想知道\R 正则表达式是否正确以及如何使 machine2 的行为符合预期。

【问题讨论】:

  • 您不必寻找\R
  • 始终使用use strict; use warnings;
  • @Shane_Yo,你在说什么?如果他的 Perl 足够新,\R 正是正确的工具。

标签: regex linux windows perl newline


【解决方案1】:

在 Perl 中,处理回车的方式有几个不同:

\n matches a line-feed (newline) character (ASCII 10)
\r matches a carriage return (ASCII 13)
\R matches any Unicode newline sequence; can be modified using verbs

Windows 使用两个字符 ASCII 13+ASCII 10 (\r\n) 而 unix 使用 ASCII 10 (\n)。 \R 表达式匹配任何 Unicode 换行序列(\r\n\r\n)。

\R 在一台机器上运行而在另一台机器上运行的可能原因可能是 Perl 的不同版本。 \R 是在perl 5.10.0 中引入的,所以如果另一台机器使用的是旧版本,那么更新应该可以解决您的问题。

更多信息

【讨论】:

    【解决方案2】:

    您的一台机器必须使用相当古老的 Perl 版本。

    5.8:

    $ perl -wle'print for split /\R/, "QRS\r\nTUV\r\n";'
    Unrecognized escape \R passed through at -e line 1.
    Q
    S
    TUV
    

    5.10:

    $ perl -wle'print for split /\R/, "QRS\r\nTUV\r\n";'
    QRS
    TUV
    

    始终使用use strict; use warnings;

    替代方案:

    • split /[\r\n]/。这与您正在使用的相同,但它可能有问题。
    • split /\n|\r\n?/。这相当于split /\R/
    • split /\r?\n/。这匹配 unix 和 Windows 行尾。
    • split /\r\n/。这与 Windows 行尾匹配。

    我会使用倒数第二个。

    【讨论】:

      【解决方案3】:

      我几乎每天都使用 Perl。

      但是,如果我所要做的只是转换行尾,那么我使用

      【讨论】:

        猜你喜欢
        • 2011-04-17
        • 1970-01-01
        • 1970-01-01
        • 2016-02-11
        • 2010-10-22
        • 1970-01-01
        • 2011-07-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多