我正在从以'713','714'等开头的文件中剥离行。我目前这样做是:

$stripped = $stripped | where{-Not $_.StartsWith('713')}
$stripped = $stripped | where{-Not $_.StartsWith('714')}
$stripped = $stripped | where{-Not $_.StartsWith('715')}
$stripped = $stripped | where{-Not $_.StartsWith('716')}
$stripped = $stripped | where{-Not $_.StartsWith('717')}

这感觉 super 草率。如何改善此代码?

最佳答案

很少有东西可以在这里工作。首先,我们可以将数组符号与您的数字序列和运算符-notin一起使用。为了进行比较,我们需要提取第一个字符以进行简单比较。

$stripped = $stripped | Where{$_.substring(0,3) -notin (713..717)}

因此,如果前三个字符在数字范围内,则将跳过它们。

对于其他解决方案,我们可以使用正则表达式,因为您的数字中存在明显的模式。您可以使用模式不匹配字符串开头的713-717中的数字。
$stripped = $stripped | where{$_ -notmatch "^71[3-7]"}

让我们说没有模式,而您只是不想在开始时使用一系列字符串。
$dontMatchMe = "^(" + ("Test","Bagel","123" -join "|") + ")"
$stripped = $stripped | where{$_ -notmatch $dontMatchMe}

脱字号^是字符串开头的正则表达式 anchor 。因此,我们构建了一个不需要的字符串数组,并使用竖线字符将它们连接起来并将其括在方括号中。在我的示例中看起来像这样:
PS C:\Users\Cameron> $dontMatchMe
^(Test|Bagel|123)

如果字符串包含正则表达式控制字符,则需要小心。

如果您对正则表达式不熟悉,那么我开始使用RexEgg会是一个很好的引用。

关于powershell - Powershell多个StartsWith子句,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31496467/

10-11 18:24