Regex Help

Tagged: 

This topic contains 3 replies, has 4 voices, and was last updated by Profile photo of Chris Bakker Chris Bakker 2 months, 2 weeks ago.

  • Author
    Posts
  • #61440
    Profile photo of Don Reese
    Don Reese
    Participant

    I had a colleague reach out to me for a little PowerShell Regex help. He has a series of filenames that have a six-digit date embedded towards the end, and I was able to initially come up with a partial solution:

    $myFileName = "backup_file_150317.txt.gz"
    $myDate = $myFileName -replace("[^\d{6}]") 
    $myDate
    

    Then, I noticed that one of the sample filenames he submitted had two sets of digits, so I came up with this:

    $myFileName = "b10202.att.150317.tar.gz"
    $myDate = ($myFileName -replace '[^\d]') -replace '.*?(?=.{6}$)'
    $myDate
    

    This seems to work, but as I'm not especially a regex wizard, I was wondering if anybody else could come up with any further optimization of the regex? I've tried a number of things to try and condense the two -replace statements and have come up empty.

  • #61441
    Profile photo of Al
    Al
    Participant

    Give this a try:

    $date = $fileName -replace '^.+(\d{6})\..+\..+$','$1'
    

    Notice that the file name must follow the pattern:

    ... six-digit dot extension dot extension

  • #61478
    Profile photo of random commandline
    random commandline
    Participant
    $string = 'b10202.att.150317.tar.gz'
    $mymatch = [regex]::Matches($string,'\d+')
    $mymatch.value[1]
    
  • #61513
    Profile photo of Chris Bakker
    Chris Bakker
    Participant

    It all depends o what filenames you have.

    "backup_file_150317.txt.gz" -match "(\d+).\w+.\w+$"
    $matches[1]

    If you have all double "extentios" on your filenames,this shoud work.

You must be logged in to reply to this topic.