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.

we enumerate through each of keys in hash. we store regex escaped version of key in $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

Popular posts from this blog

xslt - DocBook 5 to PDF transform failing with error: "fo:flow" is missing child elements. Required content model: marker* -

mediawiki - How do I insert tables inside infoboxes on Wikia pages? -

Local Service User Logged into Windows -