Powershell用字符替换转义字符

时间:2012-12-11 00:53:38

标签: regex powershell

不确定为什么以下字符串替换中的int转换为Powershell失败:

PS D:\> $b = "\x26"

PS D:\> $b -replace '\\x([0-9a-fA-F]{2})', [char][int]'0x$1'

Cannot convert value "0x$1" to type "System.Int32". Error: "Could not find any recognizable digits."
At line:1 char:1

+ $b -replace '\\x([0-9a-fA-F]{2})', [char][int]'0x$1'
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvalidCastFromStringToInteger

替换本身工作正常:

PS D:\> [char][int]($b -replace '\\x([0-9a-fA-F]{2})', '0x$1')

&

2 个答案:

答案 0 :(得分:1)

-replace运算符期望第一个字符串是要匹配的模式,并且它期望第二个参数是要替换的“字符串”。从语言规范:

7.8.4.3 The -replace operator
Description:
The -replace operator allows text replacement in one or more strings designated by 
the left operand using the values designated by the right operand. This operator has 
two variants (§7.8). The right operand has one of the following forms:
•   The string to be located, which may contain regular expressions (§3.16). In this case, the replacement string is implicitly "".
•   An array of 2 objects containing the string to be located, followed by the replacement string.

我认为在评估字符串之前你不能访问$ 1,到那时为时已晚,进行进一步的评估,即在这种情况下输入强制。

答案 1 :(得分:0)

您无法执行此操作只需-replace,但您可以使用自定义MatchEvaluator回调(docs)来执行此操作。在MatchEvaluator你有完整的代码控制权,所以你可以做任何你想做的疯狂事情!

$b = "\x26"

$matchEval = { 
  param($m)
  $charCode = $m.Groups[1].Value
  [char][int] "0x$charCode"
 }

 [regex]::Replace($b, '\\x([0-9a-fA-F]{2})', $matchEval)

>> &