Powershell 替换字符串中的字符 [英] Powershell Replace Characters in a String
问题描述
使用 powershell,但对其他潜在解决方案持开放态度....
Using powershell, but open to other potential solutions....
我有一个很长的字符串.我需要用掩码字符(句点或空格)替换该字符串中位置的几个字符序列.我不知道这些角色会是什么,但我知道他们需要是别的东西.我已经使用 mid 编写了代码,并使用 mid 和位置数字遍历字符串,但这有点麻烦,想知道是否有更快/更优雅的方法.
I have a long string. I need to replace several sequences of characters by position in that string with a mask character (period or space). I don't know what those characters are going to be, but I know they need to be something else. I have written code using mid and iterating through the string using mid and position numbers, but that is a bit cumbersome and wondering if there is a faster/more elegant method.
示例:鉴于 2 个字符串:
Example: Given the 2 strings:
ABCDEFGHIJKLMNOPQRSTUVWXYZ
12345678901234567890123456
我想替换字符 2-4, 8-9, 16-22, &23 与 .,产生:
I want to replace characters 2-4, 8-9, 16-22, & 23 with ., yielding:
A...EFGH..KLMNOP.....VWX.Z
1...5678..123456.....234.6
我可以用一系列 MID 来做到这一点,但我只是想知道是否有某种更快的屏蔽功能来实现这一点.我必须通过数百万行和第二次计数来做到这一点.
I can do that with a series of MID's, but I was just wanting to know if there were some sort of faster masking function to make this happen. I have to do this through millions of rows and second count.
推荐答案
试试这个:
$regex = [regex]'(.).{3}(.{4}).{2}(.{6}).{5}(.{3}).(.+)'
$replace = '$1...$2..$3.....$4.$5'
('ABCDEFGHIJKLMNOPQRSTUVWXYZ',
'12345678901234567890123456') -Replace $regex,$replace
A...EFGH..KLMNOP.....VWX.Z
1...5678..123456.....234.6
-replace 操作符单次操作比 string.replace() 慢,但优点是可以对字符串数组进行操作,比 string 方法加 foreach 循环要快.
The -replace operator is slower than string.replace() for a single operation, but has the advantage of being able to operate on an array of strings, which is faster than the string method plus a foreach loop.
这是一个示例实现(需要 V4):
Here's a sample implementation (requires V4):
$regex = [regex]'(.).{3}(.{4}).{2}(.{6}).{5}(.{3}).(.+)'
$replace = '$1...$2..$3.....$4.$5'
filter fix-file {
$_ -replace $regex,$replace |
add-content "c:\mynewfiles\$($file.name)"
}
get-childitem c:\myfiles\*.txt -PipelineVariable file |
get-content -ReadCount 1000 | fix-file
如果你想使用掩码方法,你可以从中生成 $regex 和 $replace :
If you want to use the mask method, you can generate $regex and $replace from that:
$mask = '-...----..------.....---.-'
$regex = [regex]($mask -replace '(-+)','($1)').replace('-','.')
$replace =
([char[]]($mask -replace '-+','-') |
foreach {$i=1}{if ($_ -eq '.'){$_} else {'$'+$i++}} {}) -join ''
$regex.ToString()
$replace
(.)...(....)..(......).....(...).(.)
$1...$2..$3.....$4.$5
这篇关于Powershell 替换字符串中的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!