在powershell中修改一个遵循特定结构的数字



在powershell中,我试图将每个电话号码的第一个号码替换为0。找到电话号码的一种方法是搜索后面跟着10位数字的号码,这就是我在下面做的。问题是,这些电话号码在文件的其他地方重复出现,没有任何结构。那么我该如何添加一个:去搜索你在文件中修改的相同数字(后面跟着的十位数(,并以相同的方式修改它们。

感谢您的帮助

$file_content = Get-Content "$original_file"
Set-Content -Path "$destination_file" -Value ($file_content -replace "d(d{9})(?=<Phone>)", "0`$1")

我认为没有更简单的方法可以做到这一点,首先获取所有与"匹配的值;CCD_ 1数字后接字CCD_,并将这些匹配项存储在哈希表中,其中是需要替换的10位,并且

0+剩余的9位然后,我们可以使用Replace(String, String, MatchEvaluator)方法来替换之前匹配的10个数字(哈希表键(的所有外观。

$string = @'
1111111111
AAA BBB 1234567890 BD 1111111111(phone)
2222222222
ABC 2222222222 CDK 23456789012 CD 2222222222(phone)
'@
$map = @{}
[regex]::Matches($string, '(?i)(d(d{9}))(phone)').ForEach({
$map[$_.Groups[1].Value] = '0' + $_.Groups[2].Value
})
[regex]::Replace($string, ($map.Keys -join '|'), {
param([string]$matched)
$map[$matched]
})

假设这是您所需要的,那么您的代码应该是这样的。

请注意,在这种情况下,必须使用-Raw开关

$map = @{}
$content = Get-Content $original_file -Raw
[regex]::Matches($content, '(?i)(d(d{9}))(phone)').ForEach({
$map[$_.Groups[1].Value] = '0' + $_.Groups[2].Value
})
$replacedContent = [regex]::Replace($content, ($map.Keys -join '|'), {
param([string]$matched)
$map[$matched]
})
Set-Content -Path $destination_file -Value $replacedContent

最新更新