0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Perl初学者】正規表現のトリミング

Posted at

本日は日記的につらつら書こうかと...

今回はPerlの正規表現を用いたトリミング技術を紹介しようと思います。

正規表現の概要についてはこちら
正規表現とは
よく使われる正規表現についてはこちら
よく使われる正規表現
を参照にどうぞ。

日付(yyyymmdd形式)に文字列をトリミングする

;hello.pl
my $date = 2022-11-08;
$date =~ s/^\s*(.*?)\s*$/$1/;#文字列をトリミング
$date =~ s/^(\d{4})-(\d{2})-(\d{2})$/$1$2$3/;#ハイフンが入っていた場合、除去する
$date =~ s/^(\d{4})\/(\d{2})\/(\d{2})$/$1$2$3/;#スラッシュ形式の場合は除去する

if ($date =~ /^(\d{4})(\d{2})(\d{2})$/){
    return print "$date\n";
};

#結果 20221108

文字列をトリミング

$date =~ s/^\s*(.*?)\s*$/$1/;
最初のsはパターンマッチs/この中を/ここに保存/という意味
今回は$1が入っているため、()中をグループ化して置換して$1に保存している

ハイフンが入っていた場合、除去する

$date =~ s/^(\d{4})-(\d{2})-(\d{2})$/$1$2$3/;
\dは0~9の文字のどれかを想定しているという意味
今度は{4(または2)}は、直前の表現(今回だったら\d)が4(2)文字を想定しているよという意味

スラッシュ形式の場合は除去する

$date =~ s/^(\d{4})\/(\d{2})\/(\d{2})$/$1$2$3/;
\/は、/を想定しているという意味

if ($date =~ /^(\d{4})(\d{2})(\d{2})$/){ return print "$date\n"; };

最後にトリミング終えた文字列を想定の正規表現と比較し、整合したら出力させる

まとめ
正規表現は奥が深くて楽しいです。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?