你知道你的分隔符是什么样子的,所以你不需要正则表达式,你需要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|
现在,显然这比其他一些答案更复杂,但它也更强大一点,因为它还允许您搜索更多键。
如果您的密钥出现多次,则此方法确实存在潜在问题。在这种情况下,很容易修改上面的代码来收集每个键的值的数组引用。