Powershell在字符和替换之间查找字符串

时间:2014-10-09 02:51:28

标签: regex string powershell replace hashtable

Powershell 脚本中,我有 Hashtable 包含个人信息。哈希表看起来像

{first = "James", last = "Brown", phone = "12345"...}

使用此哈希表,我想替换模板文本文件中的字符串。对于每个字符串匹配 @key @ 格式,我想将此字符串替换为与哈希表中的键对应的。以下是输入和输出示例:

input.txt中

My first name is @first@ and last name is @last@. 
Call me at @phone@

output.txt的

My first name is James and last name is Brown. 
Call me at 12345  

你能告诉我如何返回"关键" " @" s 之间的字符串,所以我可以找到字符串替换函数的值?欢迎任何其他关于这个问题的想法。

2 个答案:

答案 0 :(得分:3)

你可以用纯正则表达式做到这一点,但为了便于阅读,我喜欢这样做比正则表达式更多的代码:

$tmpl = 'My first name is @first@ and last name is @last@. 
Call me at @phone@'

$h = @{
    first = "James"
    last = "Brown"
    phone = "12345"
}

$new = $tmpl

foreach ($key in $h.Keys) {
    $escKey = [Regex]::Escape($key)
    $new = $new -replace "@$escKey@", $h[$key]
}

$new

说明

$tmpl包含模板字符串。

$h是哈希表。

$new将包含替换的字符串。

  1. 我们枚举哈希中的每个键。
  2. 我们在[{1}}。
  3. 中存储了密钥的正则表达式转义版本
  4. 我们使用特定键的哈希表查找替换$escKey个字符所包围的$escKey
  5. 执行此操作的一个好处是您可以更改哈希表和模板,而不必更新正则表达式。它还可以优雅地处理密钥在模板中没有相应的可替换部分的情况(反之亦然)。

答案 1 :(得分:2)

您可以使用expandable(双引号)here-string创建模板:

$Template = @"
My first name is $($hash.first) and last name is $($hash.last). 
Call me at $($hash.phone)
"@

$hash = @{first = "James"; last = "Brown"; phone = "12345"}

$Template

My first name is James and last name is Brown. 
Call me at 12345
相关问题