我试图找到最快/最有效的方法来对数组运行许多正则表达式删除。

我的$hosts数组包含成千上万个域格式的单个项目。例如:

  • test.domain.xyz
  • domain.xyz
  • something.com
  • anotherdomain.net

  • 我的$local_regex数组包含多行格式的〜1000个个人正则表达式。例如:
  • ^ ad。 (ad。*)
  • domain.xyz $(* domain.xyz)

  • 我目前正在尝试以以下方式排除任何正则表达式匹配项,但是对于大型数组和许多要匹配的正则表达式来说,它速度非常慢:
    Function Regex-Remove
    {
        Param
        (
            [Parameter(Mandatory=$true)]
            $local_regex,
            [Parameter(Mandatory=$true)]
            $hosts
        )
    
        # Loop through each regex and select only non-matching items
        foreach($regex in $local_regex)
        {
            # Multi line, case insensitive
            $regex = "(?im)$regex"
    
            # Select hosts that do not match regex
            $hosts = $hosts -notmatch $regex
        }
    
        return $hosts
    }
    

    有一个更好的方法吗?

    最佳答案

    重新分配大型阵列将耗资巨大。更改数组的大小需要分配一个新数组并将其内容复制到其中。例如,如果您拥有10000个主机名和1000个正则表达式,那么您将进行10,000万个复制操作。这将产生可测量的效果。有一个cmdlet Measure-Command,用于计时执行时间。

    作为一种替代方法,请尝试使用索引数组并用$null值覆盖不需要的值。像这样

    foreach($regex in $local_regex) {
        $regex = "(?im)$regex"
        for($i=0;$i -lt $hosts.length; ++$i) {
            if( $hosts[$i] -match $regex) {
                $hosts[$i] = $null
            }
        }
    }
    

    10-04 21:23
    查看更多