You can use the Regex.Match()
method to perform a regex match. It'll return a MatchInfo
object that has an Index
property you can use:
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
}
}
Alternatively, use the -match
operator and the $Matches
variable to grab the matched string and use that as an argument to IndexOf()
(using RedLaser's sweet regex optimization):
if($_.Name -match 's+\d{2,}e+\d{2,}')
{
$Index = $_.Name.IndexOf($Matches[0])
$ThingsBeforeMatch = $_.Name.Substring(0,$Index)
}
[Ss]+\d{2,}[Ee]+\d{2,}
or even better with the insensitive case modifier (i
):s+\d{2,}e+\d{2,}
. It matches one or mores
, then two or more digits, then one or moree
, then two or more digits. – Coopersmith