【问题标题】:Could regex be used in this PowerShell script?可以在这个 PowerShell 脚本中使用正则表达式吗?
【发布时间】:2021-12-05 22:17:52
【问题描述】:

我有以下代码,用于从字符串 $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 可以使用模式,但不清楚在这种情况下是否可行。有什么提示吗?

【问题讨论】:

    标签: regex powershell regexp-replace


    【解决方案1】:

    使用正则表达式字符类:

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

    解释

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

    【讨论】:

    • 很好,但是您缺少逐字匹配 . 字符:[ ,\n] -> [ ,\n.]
    【解决方案2】:

    这种情况的解决方案:

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

    【讨论】:

      猜你喜欢
      • 2015-03-21
      • 2012-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-27
      • 2010-09-29
      • 2021-08-11
      相关资源
      最近更新 更多