Powershell 正则表达式替换 - 使用 $1 作为字典键
Powershell regex replace - use $1 as dictionary key
我正在尝试在字符串中查找正则表达式模式并使用散列替换它 table。第一个示例工作正常,结果得到“$$oldstring$$ $$oldstring$$”。我无法弄清楚如何将“$1”作为键传递到散列 table 中,以便用与我的散列中该键对应的值替换它。
这是我的代码:
$hashtable = @{'$$oldstring$$' = 'newstring'}
$testString = '$$oldstring$$'
$replaced = [regex]::Replace($testString, '($$(.*?)$$)', ' ')
$replaced
$replaced2 = [regex]::Replace($testString, '($$(.*?)$$)', $hashtable.Get_Item())
$replaced2
并且输出:
$$oldstring$$ $$oldstring$$
Exception calling "get_Item" with "1" argument(s): "Key cannot be null.
Parameter name: key"
我知道 $hashtable.Get_Item($1) 不是有效的语法并且 $1 在这里是空的,但似乎无法弄清楚如何正确地做到这一点。
好像是我自己想出来的,不得不使用这样的脚本块:
$replaced2 = [regex]::Replace($testString, '($$(.*?)$$)', { $hashtable.Get_Item($args[0].Value) } )
更多信息在这里:
http://www.powershelladmin.com/wiki/Powershell_regular_expressions#Match_Evaluator
我正在尝试在字符串中查找正则表达式模式并使用散列替换它 table。第一个示例工作正常,结果得到“$$oldstring$$ $$oldstring$$”。我无法弄清楚如何将“$1”作为键传递到散列 table 中,以便用与我的散列中该键对应的值替换它。
这是我的代码:
$hashtable = @{'$$oldstring$$' = 'newstring'}
$testString = '$$oldstring$$'
$replaced = [regex]::Replace($testString, '($$(.*?)$$)', ' ')
$replaced
$replaced2 = [regex]::Replace($testString, '($$(.*?)$$)', $hashtable.Get_Item())
$replaced2
并且输出:
$$oldstring$$ $$oldstring$$
Exception calling "get_Item" with "1" argument(s): "Key cannot be null.
Parameter name: key"
我知道 $hashtable.Get_Item($1) 不是有效的语法并且 $1 在这里是空的,但似乎无法弄清楚如何正确地做到这一点。
好像是我自己想出来的,不得不使用这样的脚本块:
$replaced2 = [regex]::Replace($testString, '($$(.*?)$$)', { $hashtable.Get_Item($args[0].Value) } )
更多信息在这里: http://www.powershelladmin.com/wiki/Powershell_regular_expressions#Match_Evaluator