区切り文字がどのように見えるかを知っているので、正規表現は必要ありません。必要がありますsplit
。これがPerlでの実装です。
use strict;
use warnings;
my $input = "MsgNam=WMS.WEATXT|VersionsNr=0|TrxId=475665|MndNr=0257|Werk=0000|WeaNr=0171581054|WepNr=|WeaTxtTyp=110|SpraNam=ru|WeaTxtNr=2|WeaTxtTxt=100 111|";
my @first_array = split(/\|/,$input); #splitting $input on "|"
#Now, since the last character of $input is "|", the last element
#of this array is undef (ie the Perl equivalent of null)
#So, filter that out.
@first_array = grep{defined}@first_array;
#Also filter out elements that do not have an equals sign appearing.
@first_array = grep{/=/}@first_array;
#Now, put these elements into an associative array:
my %assoc_array;
foreach(@first_array)
{
if(/^([^=]+)=(.+)$/)
{
$assoc_array{$1} = $2;
}
else
{
#Something weird may be happening...
#we may have an element starting with "=" for example.
#Do what you want: throw a warning, die, silently move on, etc.
}
}
if(exists $assoc_array{TrxId})
{
print "|TrxId=" . $assoc_array{TrxId} . "|\n";
}
else
{
print "Sorry, TrxId not found!\n";
}
上記のコードは、期待される出力を生成します。
|TrxId=475665|
さて、これは明らかに他のいくつかの答えよりも複雑ですが、より多くのキーを検索できるという点でもう少し堅牢です。
キーが複数回表示される場合、このアプローチには潜在的な問題があります。その場合、上記のコードを変更して、各キーの値の配列参照を収集するのは簡単です。