可以在此 PowerShell 脚本中使用正则表达式吗?

Could regex be used in this PowerShell script?

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

它工作正常,但看起来代码很多,可以简化。我读过正则表达式可以使用模式,但不清楚在这种情况下是否可行。有什么提示吗?

使用正则表达式字符class:

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