2020年5月13日水曜日

開発環境

初めてのPerl 第7版 (Randal L. Schwartz(著)brian d foy(著)Tom Phoenix(著)近藤 嘉雪(翻訳)嶋田 健志(翻訳)、オライリージャパン)の8章(正規表現によるマッチ)、8.7(練習問題)5の解答を求めてみる。

コード

#!/usr/bin/env perl
use strict;
use warnings;
use v5.28;

say '5.';

my $label = 'word';
while (<>) {
    chomp;
    if (/(?<$label>\w+a)\b(?<other>.{1,5})/) {
        say "Matched: |$`<$&>$'|";
        say "'$label' contains '$+{$label}'.";
        say "直後に続く最大5文字 '$+{other}'";
    } else {
        say "No match: |$_|";
    }
}

入出力結果(Zsh、PowerShell、Terminal)

% cat sample.txt 
Fred
frederick
Alfred
fred flintstone
Mr. Slate
Fred
Mississippi
Bamm-Bamm
llama
wilma
fred
FRED
wilma fred
fred wilma
wilmafred
WilmaFred
barney
Mrs. Wilma flintstone
I saw Wilma Yesterday
I, Wilma!
% ./sample5.pl sample.txt 
5.
No match: |Fred|
No match: |frederick|
No match: |Alfred|
No match: |fred flintstone|
No match: |Mr. Slate|
No match: |Fred|
No match: |Mississippi|
No match: |Bamm-Bamm|
No match: |llama|
No match: |wilma|
No match: |fred|
No match: |FRED|
Matched: |<wilma fred>|
'word' contains 'wilma'.
直後に続く最大5文字 ' fred'
No match: |fred wilma|
No match: |wilmafred|
No match: |WilmaFred|
No match: |barney|
Matched: |Mrs. <Wilma flin>tstone|
'word' contains 'Wilma'.
直後に続く最大5文字 ' flin'
Matched: |I saw <Wilma Yest>erday|
'word' contains 'Wilma'.
直後に続く最大5文字 ' Yest'
Matched: |I, <Wilma!>|
'word' contains 'Wilma'.
直後に続く最大5文字 '!'
%

0 コメント:

コメントを投稿