【问题标题】:Substitute Special Characters in Word using Perl使用 Perl 替换 Word 中的特殊字符
【发布时间】:2012-07-08 23:04:38
【问题描述】:

我几乎可以替换单词中的所有特殊字符,除了以下字符:

">" - greater than symbol
"<" - less than symbol
"=" - equal to symbol

我可以通过转义其他特殊字符(如 (+[]/) 等元字符)来工作。

但是,我无法使上述 3 个特殊字符起作用。

$word =~ s/[\>\<\=]//g; # Delete these special characters from the word

如何替换它们?就我而言,我试图从单词中删除或去除特殊字符,而这 3 个符号似乎是唯一我无法替代的符号。

【问题讨论】:

标签: perl


【解决方案1】:

好吧,即使在正则表达式主体中,您也不需要转义这些符号,更不用说将它们用作字符类的一部分了。这很有效:

  my $test_string = '<my_word=some_word>';

  $test_string =~ s/[<>=]//g;
  # $test_string =~ s/<|>|=//g; is correct too, although a bit slower
  print $test_string; # my_wordsome_word

仍然是 works the same 在您的示例中编写时。所以我猜这个错误在你的代码中的其他地方。你能展示更多吗? )

【讨论】:

    【解决方案2】:

    正如其他人所指出的,您的角色在任何方面都没有什么特别之处,因此您的代码应该可以正常工作。

    我想补充一点,替换运算符可能不是从字符串中删除字符的最佳方法。无需为此调用正则表达式引擎的强大功能和复杂性。我会改为使用音译运算符(请参阅perldoc perlop 中的 tr///)。

    $ perl -E'$ARGV[0]=~ tr/<>=//d; say $ARGV[0]; ' 'a<>=b'
    ab
    

    【讨论】:

      【解决方案3】:

      和 = 没有什么特别之处,它们不是元字符,所以你甚至不需要转义它们

      perl -E'$ARGV[0]=~ s{[<>=]}{}g; say $ARGV[0]; ' 'a<>=b'
      

      给我ab

      您的问题来自其他方面

      【讨论】:

        猜你喜欢
        • 2021-07-11
        • 2015-04-29
        • 1970-01-01
        • 2020-11-21
        • 1970-01-01
        • 1970-01-01
        • 2014-11-03
        • 2011-11-17
        相关资源
        最近更新 更多