特定の数値から値を取得するにはどうすればよいですか?
数が であるとしましょう20040819
。19
Perlを使用して、つまり最後の2桁を取得したい。
my $x = 20040819;
print $x % 100, "\n";
print substr($x, -2);
ブノワの答えは的を射ており、私が使用するものですが、タイトルで提案したようにパターン検索でこれを行うには、次のようにします。
my $x = 20040819;
if ($x =~ /\d*(\d{2})/)
{
$lastTwo = $1;
}
substr("20040819", -2);
または、Regexp::Common::time - 日付と時刻の正規表現を使用できます
use strict;
use Regexp::Common qw(time);
my $str = '20040819' ;
if ($str =~ $RE{time}{YMD}{-keep})
{
my $day = $4; # output 19
#$1 the entire match
#$2 the year
#$3 the month
#$4 the day
}
さらに進んで、YYYYMMDD 形式の日付を年、月、日に抽出する方法を示します。
my $str = '20040819';
my ($year, $month, $date) = $str =~ /^(\d{4})(\d{2})(\d{2})$/;
などをチェックしてdefined $year
、一致が機能したかどうかを確認できます。
my $num = 20040819;
my $i = 0;
if ($num =~ m/([0-9]{2})$/) {
$i = $1;
}
print $i;
別のオプション:
my $x = 20040819;
$x =~ /(\d{2})\b/;
my $last_two_digits = $1;
は\b
単語境界に一致します。
あなたのための解決策:
my $number = 20040819;
my ($pick) = $number =~ m/(\d{2})$/;
print "$pick\n";
さらに別の解決策:
my $number = '20040819';
my @digits = split //, $number;
print join('', splice @digits, -2, 2);