使用 REGEX 查找捕获组中的模式;现在我需要替换/编辑找到的值。
尝试替换固定长度字段中的值:
用于搜索的正则表达式:(\d{10})(.{20}) (.+)
。
字符串是:
01234567890Alice Stone 3978 Smith st...
我必须将捕获组 2(全名)替换为 X(或者更好,但只需捕获组 2 中的名字和姓氏)
正则表达式:(\d{10})(.{20})(.+)
替换值$1xxxxxxxxxxxxxxxxxxxx$3
这可行,但我认为会有一个更迷人的解决方案(也许像 $1 x{20} $3
),或者甚至更好,只是编辑带有字母的值。
谢谢!
最佳答案
为了制定长度应与输入字符串的(可能是可变长度)子字符串匹配的替换字符串,您需要通过脚本 block 动态计算替换字符串(代表)。
在 PowerShell Core 中,您现在可以直接传递脚本 block 作为 -replace
operator 的替换操作数:
PS> '01234567890Alice Stone 3978 Smith st...' -replace
'(?<=^\d{10}).{20}', { 'x' * $_.Value.Length }
0123456789xxxxxxxxxxxxxxxxxxxx 3978 Smith st...
'(?<=^\d{10}
是一个肯定的后向断言,它匹配前 10 个数字而不捕获它们,而.{20}
匹配并捕获接下来的 20 个字符。为每个匹配调用脚本 block ,其中
$_
包含当前匹配作为[System.Text.RegularExpressions.Match]
实例;.Value
包含匹配的文本。因此,
'x' * $_.Value.Length
返回x
字符的字符串。与火柴的长度相同。
在Windows PowerShell中,您必须直接使用 [regex]
type:
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...
关于regex - 编辑捕获组值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57584362/