index参数包含。 perl的

时间:2014-05-20 08:57:50

标签: perl indexing

如果字符串包含表示任何字符的.,则索引不匹配。怎么做才能使.成为任何角色?

对于前,

index($str, $substr)

如果$substr包含.,则索引将始终返回-1

感谢

卡罗尔

3 个答案:

答案 0 :(得分:2)

这是不可能的。 documentation说:

  

索引函数在另一个字符串中搜索一个字符串,但没有   完全正则表达式模式匹配的类似通配符的行为。

     

...

您可以用于进一步谷歌搜索的关键字是:

  • perl正则表达式通配符

更新

如果您只是想知道,如果您的字符串匹配,则使用正则表达式可能如下所示:

my $string   = "Hello World!";

if( $string =~ /ll. Worl/ )
{
    print "Ahoi! Position: ".($-[0])."\n";
}

这匹配单个字符。

  

$ - [0]是整个开头字符串的偏移量   匹配。

- http://perldoc.perl.org/perlvar.html

如果你想拥有一个与任意数量的任意字符相匹配的模式,你可以选择像......这样的模式。

...

if( $string =~ /ll.*orl/ )
{

...

有关特殊perl变量的详细信息,请参阅perlvar。您会在那里找到变量@LAST_MATCH_START以及有关$-[0]的一些说明。还有几个变量可以帮助您找到子匹配并收集有关您的匹配的其他有趣信息......

答案 1 :(得分:1)

perldoc -f index开始,您可以看到index()没有任何正则表达式语法:

index STR,SUBSTR
               The index function searches for one string within another, but without the wildcard-like behavior of a full regular-
               expression pattern match.  It returns the position of the first occurrence of SUBSTR in STR at or after POSITION.  If
               POSITION is omitted, starts searching from the beginning of the string.  POSITION before the beginning of the string or after
               its end is treated as if it were the beginning or the end, respectively.  POSITION and the return value are based at 0 (or
               whatever you've set the $[ variable to--but don't do that).  If the substring is not found, "index" returns one less than the
               base, ordinarily "-1"

一个简单的测试:

$ perl -e 'print index("1234567asdfghj.","j.")'
13

答案 2 :(得分:0)

使用正则表达式:

$str =~ /$substr/g;
$index = pos();