regex可以在这个PowerShell脚本中使用吗?



我有以下代码,用于从字符串$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
}

它工作得很好,但它看起来像很多代码,可以简化。我读过regex可以与模式一起工作,但我不清楚在这种情况下是否会起作用。有提示吗?

使用一个正则表达式字符类:

Function CleanupMessage([string]$m) {
return $m -replace '[ ,.n]+', '.'
}

--------------------------------------------------------------------------------
[ ,.n]+                  any character of: ' ', ',', '.', 'n' (newline)
(1 or more times (matching the most amount
possible))

解决方案:

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*.

相关内容

  • 没有找到相关文章

最新更新