Home > Enterprise >  Could regex be used in this PowerShell script?
Could regex be used in this PowerShell script?

Time:10-19

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?

CodePudding user response:

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))

CodePudding user response:

Solution for this case:

cls
$str = "qwe asd,zxc`nufc..omg"

Function CleanupMessage([String]$m)
{
    $m -replace "( |,|`n|\.\.)", '.'
}

CleanupMessage $str

# qwe.asd.zxc.ufc.omg

Universal solution. Just enum in $toReplace what do you want to replace:

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