simon
simon

Reputation: 51

Get index of regex in filename in powershell

I'm trying to get the starting position for a regexmatch in a folder name.

dir c:\test | where {$_.fullname.psiscontainer} | foreach {
$indexx = $_.fullname.Indexofany("[Ss]+[0-9]+[0-9]+[Ee]+[0-9]+[0-9]")
$thingsbeforeregexmatch.substring(0,$indexx)
}

Ideally, this should work but since indexofany doesn't handle regex like that I'm stuck.

Upvotes: 5

Views: 11830

Answers (2)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174710

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)
}

Upvotes: 7

dugas
dugas

Reputation: 12463

You can use the Index property of the Match object. Example:

# Used regEx fom @RedLaser's comment
$regEx = [regex]'(?i)[s]+\d{2}[e]+\d{2}'
$testString = 'abcS00E00b'
$match = $regEx.Match($testString)

if ($match.Success)
{
 $startingIndex = $match.Index
 Write-Host "Match. Start index = $startingIndex"
}
else
{
 Write-Host 'No match found'
}

Upvotes: 2

Related Questions