rAJ
rAJ

Reputation: 1433

Get key value from string using Powershell

I am trying to get key value using Regex in powershell.

$string = "key1:value1,key2:value2,key3:value3"
$name = [Regex]::Matches($string, ':([^/]+),') | Select -ExpandProperty Value
Write-Host "Name :" $name

I want output like this :

$key1 = "value1"
$key2 = "value2"
$key3 = "value3"

Output i am getting :

Name : :value1,key2:value2,

Upvotes: 6

Views: 8209

Answers (4)

postanote
postanote

Reputation: 16106

I see you already have you answer, but here is one more way to do this.

("key1:value1,key2:value2,key3:value3").Split(',') | 
%{$PSItem | ConvertFrom-Csv -Delimiter ':' -Header Name, Value}

# Results

Name Value 
---- ----- 
key1 value1
key2 value2
key3 value3

Upvotes: 1

Robert Dyjas
Robert Dyjas

Reputation: 5227

Pretty sure that sysg0blin's helpful answer can do the job, but if you really want to set specific variables this can be done with such script:

$string = "key1:value1,key2:value2,key3:value3"
$splitted = $string -split ','
$splitted | ForEach-Object {
  $i = $_ -split ":"
  Set-Variable -Name $i[0] -Value $i[1]
}

What you do here is to split string into array of key:value pair and then split each pair into array with 2 elements, first being variable name and second being value of the variable.

Upvotes: 4

sysg0blin
sysg0blin

Reputation: 416

If you are using the comma to separate the key:value pairs this should accomplish what you are after.

$string = "key1:value1,key2:value2,key3:value3"
$ht = @{} # declare empty hashtable
$string -split ',' | % { $s = $_ -split ':'; $ht += @{$s[0] =  $s[1]}} 
# split the string by ',', then split each new string on ':' and map them to the hashtable

Outputs the following (note by default they are not ordered)

PS C:\> $ht

Name                           Value
----                           -----
key3                           value3
key1                           value1
key2                           value2

Upvotes: 7

The fourth bird
The fourth bird

Reputation: 163517

You get that match because there is no match before the : and [^/]+ will also match : and ,.

So your pattern will first match :, then it will match not a / and then backtracks until it can match a ,

You could use 2 times a negated character class matching not a comma or colon and assert what is on the right is a comma or the end of the string:

[^:,]+:[^:,]+(?=,|$)

Regex demo

If you also don't want to match a / you could add it to the character class:

[^:,/]+:[^:,/]+(?=,|$)

Upvotes: 1

Related Questions