我试图在文件夹名称中获取正则表达式的起始位置;
dir c:\test | where {$_.fullname.psiscontainer} | foreach {
$indexx = $_.fullname.Indexofany("[Ss]+[0-9]+[0-9]+[Ee]+[0-9]+[0-9]")
$thingsbeforeregexmatch.substring(0,$indexx)
}
理想情况下,这应该可行,但因为 indexofany 不能像我那样处理正则表达式。
最佳答案
您可以使用 Regex.Match()
method 执行正则表达式匹配。它将返回一个 MatchInfo
对象,该对象具有您可以使用的 Index
属性:
Get-ChildItem c:\test | Where-Object {$_.PSIsContainer} | ForEach-Object {
# Test if folder's Name matches pattern
$match = [regex]::Match($_.Name, '[Ss]+[0-9]+[0-9]+[Ee]+[0-9]+[0-9]')
if($match.Success)
{
# Grab Index from the [regex]::Match() result
$Index = $Match.Index
# Substring using the index we obtained above
$ThingsBeforeMatch = $_.Name.Substring(0, $Index)
Write-Host $ThingsBeforeMatch
}
}
或者,使用
-match
运算符和 $Matches
变量来获取匹配的字符串并将其用作 IndexOf()
的参数(使用 RedLaser's sweet regex optimization ):if($_.Name -match 's+\d{2,}e+\d{2,}')
{
$Index = $_.Name.IndexOf($Matches[0])
$ThingsBeforeMatch = $_.Name.Substring(0,$Index)
}
关于regex - 在powershell中获取文件名中正则表达式的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35213219/