regex - Powershell Find String Between Characters and Replace -
regex - Powershell Find String Between Characters and Replace -
in powershell script, have hashtable contains personal information. hashtable looks like
{first = "james", lastly = "brown", phone = "12345"...}
using hashtable, replace strings in template text file. each string matches @key@ format, want replace string value correspond key in hashtable. here sample input , output:
input.txt
my first name @first@ , lastly name @last@. phone call me @ @phone@
output.txt
my first name james , lastly name brown. phone call me @ 12345
could advise me how homecoming "key" string between "@"s can find value string replacement function? other ideas problem welcomed.
you pure regex, sake of readability, doing more code regex:
class="lang-poweshell prettyprint-override">$tmpl = 'my first name @first@ , lastly name @last@. phone call me @ @phone@' $h = @{ first = "james" lastly = "brown" phone = "12345" } $new = $tmpl foreach ($key in $h.keys) { $esckey = [regex]::escape($key) $new = $new -replace "@$esckey@", $h[$key] } $new
explanation $tmpl
contains template string.
$h
hashtable.
$new
contain replaced string.
$esckey
. we replace $esckey
surrounded @
characters hashtable lookup particular key. one of nice things doing can alter hashtable , template, , never have update regex. gracefully handle cases key has no corresponding replacable section in template (and vice-versa).
regex string powershell replace hashtable
Comments
Post a Comment