関数順 インデックス
目的別 インデックス

構文
 
 rindex 文字列, 検索文字列,検索開始位置
 rindex 文字列, 検索文字列

返り値
 
 検索文字列の出現位置

説明

  • 指定した文字列の中で,検索文字列が最後に出現する位置を返します。開始位置が指定してある場合にはその位置から探し始めます。省略した場合は末尾から探し始めます。
  • 検索文字列が見つからない場合には-1を返します。

使用例

変数$str中にmoneyという文字列が含まれる場合はFound.を含まれない場合はNot found.を表示する
#!/usr/bin/perl
use strict;
use warnings;

my $str = 'A fool and his money are soon parted.';
my $search = 'money';

my $pos = rindex $str, $search;
if ($pos > -1) {
  print "Found.\n";
} else {
  print "Not found.\n";
}
変数$str中にmoneyという文字列が含まれる位置を調べて表示する。文字列が含まれない場合はNot found.と表示する
#!/usr/bin/perl
use strict;
use warnings;

my $str = 'It takes money to make money.';
my $search = 'money';

my $pos = index $str, $search;
if ($pos > -1) {
  my $rpos = rindex $str, $search;
  printf "前方から探した場合の発見位置[%d]\n", $pos;
  printf "後方から探した場合の発見位置[%d]\n", $rpos;
} else {
  print "Not found.\n";
}
※前から調べる場合はindexを使います。

変数$str中にmoneyという文字列が含まれる場合はFound.を含まれない場合はNot found.を表示する
#!/usr/bin/perl
use strict;
use warnings;

my $str = 'A fool and his money are soon parted.';
my $search = qr/money/;

if ($str =~ m/$search/) {
  print "Found.\n";
} else {
  print "Not found.\n";
}
※文字列が含まれるかどうかはm//を使って調べることもできます。