/ / WinChalow

正規表現の自動生成 その2[perl]

2004-12-17

文字列はすべて '.*' に変換するのをデフォルトとして、ユーザーが指定したセパレータのみを特別扱いするという戦略を採用してみるテスト。

ChangeLog フォーマットのアイテム・ヘッダーの正規表現を作らせてみた。

#!/usr/bin/perl -w
# $Id: genreg3.pl,v 1.1 2004/12/17 04:33:44 zuihu Exp $
# This script should be saved in UTF-8.

require 5.008;
use strict;
use utf8;
use Encode qw(encode);

# ここからユーザー指定項目 #
# 例示文字列
my $ex = "\t* CGI 開発ツール KCatch.pm [perl]:";
# 制約
my @separators = qw( \[ \] ); # 文字列として一般化しない記号
my $head = '\t\* '; # 頭部指定
my $tail = '\:'; # 尾部指定
# ここまでユーザー指定項目 #

print encode('Shift_JIS', $ex), "\n";

# 下準備
my $text = $ex;
$text =~ s/^($head)// if ($head && $head ne "");
$text =~ s/($tail)$// if ($tail && $tail ne "");

# 本作業
$text =~ s/([^\[\]]+)/(\.\*)/og;
for my $s (@separators)
{
$text =~ s/$s/\\$s/g;
$text =~ s/\\\\/\\/g;
}
my $pat = '^(' . $head . ')' if ($head && $head ne "");
$pat .= $text;
$pat .= $tail . '$' if ($tail && $tail ne "");

print encode('Shift_JIS', $pat), "\n";

# できあがった正規表現をテスト
$ex = "Regex NG." unless $ex =~ s/$pat/Regex OK./;
print encode('Shift_JIS', $ex), "\n";


スクリプトの出力
\t* CGI 開発ツール KCatch.pm [perl]:
^(\t\* )(.*)\[(.*)\]\:$
Regex OK.

だいぶ手間がはぶけるように思うのは私だけだろうか。

(2004-12-17 13:51:12)

permlink