Perl和元字符中的斜杠和散列

时间:2011-02-15 17:48:55

标签: regex perl

我早些时候曾询问有关转义特殊字符并理解围绕//和##的规则但下面的示例不起作用,而且根据我的理解,我需要转义逃生字符。它被搜索为匹配它的名称之间\的通常含义。我很难过。请帮忙。尽管可能对大众来说很容易,但这让我很开心。我知道我可以写成$ userInfo =〜#\#;

#!C:\strawberry\perl\bin\perl.exe

#strict
#diagnostics


$userInfo = "firstname\middlename\lastname.";


if($userInfo =~ m/\\/){ 
print("Found it");
}

else{
print("No match found");
}

3 个答案:

答案 0 :(得分:5)

问题是您必须在$userInfo作业中转义反斜杠:

$userInfo = "firstname\\middlename\\lastname.";

答案 1 :(得分:3)

您正在尝试搜索包含文字bakslash字符\的字符串。双引号插值。改为使用单引号。

use warnings;
use strict;

my $userInfo = 'firstname\middlename\lastname.';

if ($userInfo =~ m/\\/){
    print("Found it");
}
else{
    print("No match found");
}

警告pragma会产生警告信息。

另请参阅:Quote and Quote-like Operators

答案 2 :(得分:1)

我同意工具,如果可以,请使用单引号 它将节省字符串插值所需的一些预处理时间。

但是,如果你真的需要转义特殊字符,你可以这样写:

  #!C:\strawberry\perl\bin\perl.exe

  #strict
  #diagnostics

  $userInfo = "firstname\\middlename\\lastname.";      #please note escaped backslahes
  if($userInfo =~ m/\\/)
  { 
    print("Found it");
  }
  else
  {
    print("No match found");
  }