为了制定一个替换字符串,其长度应该匹配输入字符串的一个 - 可能是可变长度 - 子字符串,您需要通过脚本块(委托)动态计算替换字符串。
在 PowerShell Core中,您现在可以直接将脚本块作为-replace
operator的替换操作数传递:
PS> '01234567890Alice Stone 3978 Smith st...' -replace
'(?<=^\d{10}).{20}', { 'x' * $_.Value.Length }
0123456789xxxxxxxxxxxxxxxxxxxx 3978 Smith st...
在Windows PowerShell中,您必须直接使用该[regex]
类型:
PS> [regex]::Replace('01234567890Alice Stone 3978 Smith st...',
'(?<=^\d{10}).{20}', { param($m) 'x' * $m.Value.Length })
0123456789xxxxxxxxxxxxxxxxxxxx 3978 Smith st...
如果预先知道要替换的子字符串的长度- 如您的情况 - 您可以更简单地执行以下操作:
PS> $len = 20; '01234567890Alice Stone 3978 Smith st...' -replace
"(?<=^\d{10}).{$len}", ('x' * $len)
0123456789xxxxxxxxxxxxxxxxxxxx 3978 Smith st...
无条件地编辑所有字母更加简单:
PS> '01234567890Alice Stone 3978 Smith st...' -replace '\p{L}', 'x'
01234567890xxxxx xxxxx 3978 xxxxx xx...
\p{L}
匹配任何 Unicode 字母。
仅在匹配的子字符串中编辑字母需要嵌套一个-replace
操作:
PS> '01234567890Alice Stone 3978 Smith st...' -replace
'(?<=^\d{10}).{20}', { $_ -replace '\p{L}', 'x' }
01234567890xxxxx xxxxx 3978 Smith st...