【问题标题】:Why can't I replace all in a string and instead I get back an empty string?为什么我不能替换字符串中的所有内容,而是返回一个空字符串?
【发布时间】:2013-10-09 17:43:58
【问题描述】:

我正在尝试用新行替换所有出现的回车,新行,但我不能。
正在尝试:my $new_string = $old_string =~ s/\r\n/\n/g
给出一个空的$new_sting
这:my $new_string = $old_string =~ s/\r\n$/\n/g 也无法提供空字符串。
我在这里搞砸了什么?

【问题讨论】:

    标签: regex string perl replace


    【解决方案1】:

    您最初尝试的问题是$old_string 与替换运算符绑定(因此将修改的是该变量),然后替换运算符的返回值变为它成功匹配的次数。该匹配计数放在$new_string 中,如果匹配失败,则使用空字符串表示零计数。

    您最初的尝试将在支持 /r 修饰符的最新版本的 Perl 中正常工作,只需稍作修改:

    my $new_string = $old_string =~ s/\r\n/\n/gr;
    

    该修饰符触发替换运算符的“非破坏性”模式,并返回修改后的字符串而不是计数。 /r 修饰符是在 Perl 5.14 中引入的,并在 perlop 中进行了描述。

    在旧版本的 Perl 中,括号可用于操作优先级:

    ( my $new_string = $old_string ) =~ s/\r\n/\n/g
    

    此语法首先评估my $new_string = $old_string,然后使用$new_string 与替换绑定。

    【讨论】:

      【解决方案2】:

      这个

      my $new_string = $old_string =~ s/\r\n/\n/g
      

      返回 number 个替换,而不是 新字符串。要查看新字符串,只需替换后的print $old_string


      来自perlop

      s/PATTERN/REPLACEMENT/msixpodualgcer
      

      在字符串中搜索模式,如果找到,则用替换文本替换该模式并返回进行的替换次数否则返回 false(特别是空字符串)。如果使用 /r (非破坏性)选项,则它会在字符串的副本上运行替换,而不是返回替换的数量,而是返回是否发生替换的副本。使用 /r 时,原始字符串永远不会更改。副本将始终是纯字符串,即使输入是对象或绑定变量。

      【讨论】:

      • 但是当我打印 $new_string 时,我没有看到 0。我什么也没看到
      • 因为当没有匹配项时,$new_string 什么也不返回!
      【解决方案3】:

      $old_string$new_string 上的替换仅包含已完成的替换次数,因此请使用括号更改操作的优先级,

      (my $new_string = $old_string) =~ s/\r\n/\n/g;
      

      【讨论】:

      • 这和我做的有什么不同?
      • @Jim 优先级不同
      猜你喜欢
      • 2012-03-17
      • 2023-03-14
      • 2020-05-09
      • 1970-01-01
      • 2013-01-19
      • 2017-09-04
      • 1970-01-01
      • 2022-08-04
      • 1970-01-01
      相关资源
      最近更新 更多