Regex & Substring() To Get Part of File Name

This topic contains 3 replies, has 2 voices, and was last updated by Profile photo of Aaron Hardy Aaron Hardy 3 months, 1 week ago.

  • Author
    Posts
  • #52593
    Profile photo of Aaron Hardy
    Aaron Hardy
    Participant

    I have different types of files that all have the date in the filename (YY-MMDD), and I need to extract only the date portion and use for further execution (? = may or may not have character, depending on type of file):

    ?YY-MMDD?.???

    The Split() method portion below works, but now I need to assign only the date portion to a variable and leave the other characters out. Though likely quite simple, I've tried many regex's but my regex saw needs a lot of sharpening.

    if ($FileName -match "\d{2}-\d{4}")
    {
         $Label = $FileName.Split('.')[0]
    
         # assign date to variable here
    }
    

    Thank you for any help.

    Aaron

  • #52605
    Profile photo of Craig Duff
    Craig Duff
    Participant
    $test = @(
    '16-0830.txt'
    'randomtext16-0830.txt'
    '16-0830randomtext.txt'
    'randomtext16-0830randomtext.txt'
    '1234516-083012345.txt'
    )
    
    ForEach($item in $test)
    {
        If($item -match "(?'date'\d{2}-\d{4})")
        {
            "$item's date is $($Matches['date'])"
        }
        Else
        {
            "$item failed to match"
        }
    }

    Just need a capturing group.

  • #52607
    Profile photo of Craig Duff
    Craig Duff
    Participant

    If you were using get-childitem to get the file names, there isn't a need to use the .split(). The returned object will come with a BaseName property that already has the file type extension removed.

  • #52750
    Profile photo of Aaron Hardy
    Aaron Hardy
    Participant

    Thanks Craig!

    That's exactly what was needed. You can see I was essentially missing (?'date'\d{2}-\d{4}) – another simple fix.

    Appreciate the help!

    Aaron

You must be logged in to reply to this topic.