Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 843
simon Avatar asked Mar 13 '23 09:03

simon


2 Answers

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)
}
like image 75
Mathias R. Jessen Avatar answered Mar 19 '23 02:03

Mathias R. Jessen


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'
}
like image 41
dugas Avatar answered Mar 19 '23 03:03

dugas