Get index of regex in filename in powershell
Asked Answered
T

2

5

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.

Typesetter answered 4/2, 2016 at 22:51 Comment(1)
Bonus: you can simplify that regex to [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 more s, then two or more digits, then one or more e, then two or more digits.Coopersmith
S
7

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)
}
Sealed answered 4/2, 2016 at 23:15 Comment(2)
Hey Mathias, related question, How would you get the entire string after the match, so i can feed this string back into the Match again in a loop to iterate over all patterns matching in the string?Incarnation
@Incarnation $Match.Value contains the matched substring, the original string is stored in $_.Name. I'm afraid I don't understand the last part of your question :)Sealed
A
2

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'
}
Allcot answered 4/2, 2016 at 23:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.