1

不知道为什么在以下字符串替换中强制转换为 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')

&
4

2 回答 2

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 ,到那时进行进一步评估为时已晚,即在这种情况下类型强制。

于 2012-12-11T01:15:22.613 回答
0

你不能这样做是 single -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)

>> &
于 2012-12-11T18:04:45.367 回答