你知道你的分隔符是什麼樣子,所以你並不需要一個正則表達式,你需要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|
現在,很明顯這是比一些其他的答案比較複雜,但它也有點更強大的,它允許你搜索更多的關鍵。
如果您的密鑰出現多次,此方法確實存在潛在問題。在這種情況下,修改上面的代碼很容易,可以爲每個密鑰收集一個值爲array reference的值。
哪種語言,你在做這個?可能比正則表達式更容易/更好。 – Bojangles
@JamWaffles我不認爲有更好的辦法,你可以拆分和循環陣列,但我不認爲這會是一個巨大的速度增加,因爲這個正則表達式有點O(n)其中n是字符串長度。 –