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,
To find a string inside of a string with PowerShell, you can use the Substring() method. This method is found on every string object in PowerShell. The first argument to pass to the Substring() method is the position of the leftmost character. In this case, the leftmost character is T .
@{} in PowerShell defines a hashtable, a data structure for mapping unique keys to values (in other languages this data structure is called "dictionary" or "associative array"). @{} on its own defines an empty hashtable, that can then be filled with values, e.g. like this: $h = @{} $h['a'] = 'foo' $h['b'] = 'bar'
Split() function splits the input string into the multiple substrings based on the delimiters, and it returns the array, and the array contains each element of the input string. By default, the function splits the string based on the whitespace characters like space, tabs, and line-breaks.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With