【问题标题】:perl: index query containing unspecified charactersperl:包含未指定字符的索引查询
【发布时间】:2016-02-06 16:43:32
【问题描述】:

我想使用 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 

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

【问题讨论】:

  • 您想计算重叠匹配吗?例如,如果字符串是aaa,查询是aa,你会返回两个匹配项(索引0 和1)还是只返回一个匹配项(索引0)?
  • 始终 use strictuse warnings 'all' 在您编写的每个 Perl 程序的开头,尤其是在寻求帮助之前。这项措施会直接为您指出问题的答案

标签: perl indexing match


【解决方案1】:

\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";
}

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

【讨论】:

【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多