我想知道在Powershell中将某个字符串解析为哈希的最简洁方法是什么。
这是我到目前为止所做的:
PS D:\Videos> $x
Track ID 1: audio (AC3/EAC3) [number:2 uid:1938239150 codec_id:A_AC3 codec_private_length:0 language:heb default_track:1 forced_track:0 enabled_track:1 default_duration:32000000 audio_sampling_frequency:48000 audio_channels:6]
PS D:\Videos> $hash = @{}
PS D:\Videos> $x -match "^.*\[(.*)\]" | ForEach-Object { $Matches[1] -split ' ' |% { $tmp = $_ -split ':'; $hash[$tmp[0]] = $tmp[1] } }
PS D:\Videos> $hash
Name Value
---- -----
audio_sampling_frequency 48000
codec_private_length 0
audio_channels 6
number 2
default_duration 32000000
forced_track 0
enabled_track 1
language heb
codec_id A_AC3
uid 1938239150
default_track 1
PS D:\Videos>
它完成了这项工作,但在我看来应该有一个更短的方式。
我说错了吗?
答案 0 :(得分:3)
对于这种特殊情况,这段代码有点短:
$hash = @{}
foreach($m in [regex]::Matches($x, '(\w+):(\w+)')) {
$hash[$m.Groups[1].Value] = $m.Groups[2].Value
}
$hash
答案 1 :(得分:3)
另一种可能性:
$string = 'Track ID 1: audio (AC3/EAC3) [number:2 uid:1938239150 codec_id:A_AC3 codec_private_length:0 language:heb default_track:1 forced_track:0 enabled_track:1 default_duration:32000000 audio_sampling_frequency:48000 audio_channels:6]'
$Hash = ConvertFrom-StringData ($string -replace '^.+\[(.+)\]','$1').replace(':','=').replace(' ',"`n")
$Hash
Name Value
---- -----
enabled_track 1
codec_id A_AC3
default_duration 32000000
audio_channels 6
uid 1938239150
language heb
default_track 1
audio_sampling_frequency 48000
forced_track 0
number 2
codec_private_length 0
答案 2 :(得分:0)
$t="Track ID 1: audio (AC3/EAC3) [number:2 uid:1938239150 codec_id:A_AC3 codec_private_length:0 language:heb default_track:1 forced_track:0 enabled_track:1 default_duration:32000000 audio_sampling_frequency:48000 audio_channels:6]"
$h=@{}
foreach($record in $t.Split('[]')[1].Split(' ')) {
$key, $value = $record.Split(':')
$h.$key=$value
}
$h