我有以下代碼,用于從字串 $m 中洗掉空格和其他字符,并用句點 ('.') 替換它們:
Function CleanupMessage([string]$m) {
$m = $m.Replace(' ', ".") # spaces to dot
$m = $m.Replace(",", ".") # commas to dot
$m = $m.Replace([char]10, ".") # linefeeds to dot
while ($m.Contains("..")) {
$m = $m.Replace("..",".") # multiple dots to dot
}
return $m
}
它作業正常,但看起來代碼很多,可以簡化。我讀過正則運算式可以處理模式,但不清楚在這種情況下是否可行。任何提示?
uj5u.com熱心網友回復:
使用正則運算式字符類:
Function CleanupMessage([string]$m) {
return $m -replace '[ ,\n] ', '.'
}
解釋
--------------------------------------------------------------------------------
[ ,\n] any character of: ' ', ',', '\n' (newline)
(1 or more times (matching the most amount
possible))
uj5u.com熱心網友回復:
這種情況的解決方法:
cls
$str = "qwe asd,zxc`nufc..omg"
Function CleanupMessage([String]$m)
{
$m -replace "( |,|`n|\.\.)", '.'
}
CleanupMessage $str
# qwe.asd.zxc.ufc.omg
通用解決方案。只需列舉$toReplace您要替換的內容:
cls
$str = "qwe asd,zxc`nufc..omg kfc*fox"
Function CleanupMessage([String]$m)
{
$toReplace = " ", ",", "`n", "..", " ", "fox"
.{
$d = New-Guid
$regex = [Regex]::Escape($toReplace-join$d).replace($d,"|")
$m -replace $regex, '.'
}
}
CleanupMessage $str
# qwe.asd.zxc.ufc.omg.kfc*.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/323307.html
