我有一个替换变音符号的功能。如果该功能另存为普通脚本文件(.ps1),则输出为test-aeoeueAeOeUe1234
。这就是我期望得到的:-)
function TestReplace{
Param(
[parameter(Mandatory=$true,Position=0)][ValidateNotNullOrEmpty()][String]$InputString
)
$ResultString = ($InputString.replace('ä', 'ae').replace('ö','oe').replace('ü','ue').replace('Ä', 'Ae').replace('Ö','Oe').replace('Ü','Ue'))
$ResultString
}
TestReplace -InputString "test-äöüÄÖÜ1234"
但是,如果将相同的函数保存为模块(.psm1)的一部分,则结果为test-aeoeueaeoeue1234
-似乎replace函数不区分大小写。
我不知道为什么相同的代码导致不同的输出...
答案 0 :(得分:0)
在处理这样的字符时,最好将字符串转换为字符数组并处理整数字符代码,字符串解释可能因主机而异。在C#中检出this answer。
我已将该解决方案移植到PowerShell功能,希望对您有所帮助:
function Replace-Diacritics {
param
(
$InputString
)
$dictionary = @{
228 = "ae" # [int][char]'ä'
246 = "oe" # [int][char]'ö'
252 = "ue" # [int][char]'ü'
196 = "Ae" # [int][char]'Ä'
214 = "Oe" # [int][char]'Ö'
220 = "Ue" # [int][char]'Ü'
223 = "ss" # [int][char]'ß'
}
$sb = New-Object -TypeName "System.Text.StringBuilder";
$null = ($InputString.ToCharArray() | % { if($dictionary[[int]$_]) { $sb.Append($dictionary[[int]$_]) } else { $sb.Append($_) } });
return $sb.ToString();
}
$input = "test-äöüÄÖÜ1234";
$expected = "test-aeoeueAeOeUe1234";
$result = Replace-Diacritics $input;
if($result -eq $expected)
{
Write-Host "Test passed. Expected: $expected, Actual: $result" -ForegroundColor Green
}
else
{
Write-Host "Test failed. Expected: $expected, Actual: $result" -ForegroundColor Red
}