perl:包含未指定字符的索引查询

时间:2015-11-05 17:52:59

标签: perl indexing match

我想在perl中使用index函数找到所有匹配的位置。棘手的部分是我的查询里面有可变字母(我在这里使用一个简单的例子)。

my $query="b\wll"; 
my $string= "I see a ball on a bull";

my $output = index($string, $query, $offset); 
while ($output != -1) {

        print "$char\t$output\n";

我想要的输出是

ball  8
bull  18 

它应该看起来像这样,但我不能让它工作。能否请你帮忙 ?

2 个答案:

答案 0 :(得分:3)

\w未在双引号字符串文字中定义。

$ perl -wE'say "b\wll";'
Unrecognized escape \w passed through at -e line 1.
bwll

要创建字符串b\wll,您需要

"b\\wll"

在这种情况下,您还可以使用以下内容,因为您正在创建正则表达式模式:

qr/b\wll/

这样就解决了第一个问题,但第二个问题是:index对正则表达式一无所知。您需要使用匹配运算符。

my $pattern = "b\\wll"; 
my $string = "I see a ball on a bull";

while ($string =~ /($pattern)/g) {
   print "$-[1]\t$1\n";
}

在标量上下文中使用匹配运算符时,我们可以使用@-查看每个匹配项的匹配位置。

答案 1 :(得分:0)

查找所有匹配项以及之前的文本,然后将字符串长度相加:

perl -E '
  my $query = q{b\wll};
  my $string = qq{I see a ball on a bull};
  my @matches = $string =~ /(.*?)($query)/g;
  $, = qq{\t};
  for (my ($pos, $i) = (0,0); $i < @matches; $i+=2) {
    $pos += length $matches[$i];
    say $matches[$i+1], $pos;
    $pos += length $matches[$i+1];
  }
'
ball    8
bull    18