Search code examples
regexpowershellregexp-replace

Could regex be used in this PowerShell script?


I have the following code, used to remove spaces and other characters from a string $m, and replace them with periods ('.'):

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
}

It works OK, but it seems like a lot of code and can be simplified. I've read that regex can work with patterns, but am not clear if that would work in this case. Any hints?


Solution

  • Use a regex character class:

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

    EXPLANATION

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