1

我的脚本中有以下代码。

if($description =~ /\'/) {
    print "I am here\n";    
    $description =~ s/\'/'/g;
}
print "description = $description\n";

"I am here\n"当我运行这个脚本时,由于比较失败,我没有得到输出。

但是,当$description字符串确实包含撇号时。

$description = "The baseball player’s spiritual redemption and recovery from drug addiction.";

上下文:我正在解析从调用 nytimes bestsellers api 获得的字符串(以 json 格式返回),并且该字符串存储在$description字符串中。

4

2 回答 2

6

您的示例字符串不包含撇号。它包含一个U+2019 RIGHT SINGLE QUOTATION MARK.

它应该匹配/\x{2019}/

于 2012-08-22T18:26:19.340 回答
0

您不需要在正则表达式中转义引号。稍微改变你的代码:

use strict;
use warnings;

my $description="The baseball player's spiritual redemption and recovery from drug addiction.";

if($description =~ /'/)
{
        print "I am here\n";
        $description =~ s/'/foo/g;
}

print "description = $description\n";

产生以下输出:

I am here
description = The baseball playerfoos spiritual redemption and recovery from drug addiction.
于 2012-08-22T18:11:14.477 回答