如何根据字符串中出现的内容过滤列表

时间:2020-09-24 14:41:08

标签: regex powershell

我有一系列这样的物品:

get-childitem *\bin\Release\*Tests.dll -recurse

我有这样的路径:

C:\r\x\ABCTests\bin\Release\net461\ABCTests.dll
C:\r\x\ABCTests\bin\Release\net461\OtherTests.dll
C:\r\x\OtherTests\bin\Release\net461\OtherTests.dll

我只希望文件名与文件夹名匹配的路径:

C:\r\x\ABCTests\bin\Release\net461\ABCTests.dll - Yes
C:\r\x\ABCTests\bin\Release\net461\OtherTests.dll - No
C:\r\x\OtherTests\bin\Release\net461\OtherTests.dll - Yes

在Powershell中进行过滤的最佳方法是什么?我尝试使用Select-String,但是它会打开文件。我已经准备好正则表达式,因为在Powershell中执行时遇到问题。我应该使用正则表达式吗?

以下是powershell代码:

get-childitem *\bin\Release\*Tests.dll -recurse | Where-Object { $_.FullName -match {"(" + $_.Name.Substring(0, $_.Name.LastIndexOf(".")) + ").*\1\.dll"} } | %{ write-host $_ }

1 个答案:

答案 0 :(得分:1)

我建议使用

$rx = '\\([^\\]*)Tests\\bin\\Release\\(?:.*\\)?\1Tests\.dll$'

请参见regex demo

正则表达式详细信息

  • \\-一个\字符
  • ([^\\]*)-第1组:除反斜杠外的任何零个或多个字符
  • Tests\\bin\\Release\\-Tests\bin\Release\的文本(由于该值已在全局字段中使用,我们可能会对其进行硬编码)
  • (?:.*\\)?-任意一个0或多个字符的可选序列,除了换行符,该字符应尽可能多,然后使用反斜杠
  • \1-与第1组中捕获的值相同
  • Tests\.dll-Tests.dll字符串(由于该值已在全局字段中使用,我们可能会对其进行硬编码)
  • $-字符串的结尾。

然后使用

Get-Childitem *\bin\Release\*Tests.dll -recurse | 
  Where { $_.FullName -match $rx } | 
    % { $_.FullName }

请参见regex demo