Extract Key Value from string

Viewed 112

I have the following code:

$myString = "Name=Tony;Fee=10;Account=Premium"
$splitString = "$($myString)".Split(";")

$name = $splitString -match "Name=(?<content>.*)"
$acct = $splitString -match "Account=(?<content>.*)"

$name 
$acct

Result:

Name=Tony
Account=Premium

How can I get it to return just the value? Example:

Tony
Premium

Thanks in advance

3 Answers

Combine -split, the string splitting operator, with a switch statement and its -Regex switch:

$name, $acct = 
  switch -Regex ("Name=Tony;Fee=10;Account=Premium" -split ';') {
    '^(?:Name|Account)=(?<content>.*)' { $Matches['content'] }
  }

Here's another approach using -Split and taking advantage of the text's format using ConvertFrom-StringData

$name, $acct = "Name=Tony;Fee=10;Account=Premium" -split ';' |
    ConvertFrom-StringData | ForEach-Object {$_.name,$_.Account}

I would use -split here to to construct a hashtable of key value pairs:

$myString = "Name=Tony;Fee=10;Account=Premium"

# Create hashtable
$ht = @{}

# Spit string by ';' and loop over each item
foreach ($item in $myString -split ';') {

    # Split item by '=' to get key value pair
    $pair = $item -split '='

    # Set key value pair into hashtable
    $ht[$pair[0]] = $pair[1]
}

# Output values you want
$ht.Name
$ht.Account

# Tony
# Premium

Which also is beneficial if you need to lookup other values.

Related