finding timein a string

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

  • Author
    Posts
  • #69699
    Profile photo of Futureofandhra
    Futureofandhra
    Participant

    1).Every 15 minutes between 3:00am and 9:00pm every day
    2)Every 2 hour(s) between 6:30:00 AM and 9:30:00 PM.
    3)Every hour between 6:30:00 AM and 9:30:00 PM.
    4)Runs at 4:30am, noon, and 4 PM.

    I have strings like above
    I want to get time from those strings like below
    1). 15 minutes, 3:00 am , 9:00 pm
    2).2 hours, 6:30:00 AM,9:30:00 PM.
    3). hour, 6:30:00 AM,9:30:00 PM.
    4).4:30am, noon ,4 PM

    I have tried using $Time.Split("")[4] +" "+ $Time.Split("")[5] but it did not work because the string is changing in all the formats

    So i wanted to find time time in the string.

    But no idea.need help on this

  • #69709
    Profile photo of Matt Bloomfield
    Matt Bloomfield
    Participant

    To do this you need to use regular expressions. If those are the only string formats you have then I think it's actually going to be easier to replace the text you don't want rather than search for the text you're after – it took me less time to figure out how to do it that way 🙂

    Get-Help about_regular_expressions

    $strings = 'Every 15 minutes between 3:00am and 9:00pm every day','Every 2 hour(s) between 6:30:00 AM and 9:30:00 PM.','Every hour between 6:30:00 AM and 9:30:00 PM.','Runs at 4:30am, noon, and 4 PM.'
    
    foreach ($string in $strings) {
    
        $string = ($string -replace "Every|Between|and|day|Runs|at|\.|\,"," ").trim() -replace "\s{2,}",","    
    
        Write-Output $string
    }
    
    
  • #69727
    Profile photo of Roy Atkins
    Roy Atkins
    Participant

    I agree with Matt. Removing what you don't need is sometimes preferable. Otherwise you could be stuck with maintaining this:

    $strings = 'Every 15 minutes between 3:00am and 9:00pm every day','Every 2 hour(s) between 6:30:00 AM and 9:30:00 PM.','Every hour between 6:30:00 AM and 9:30:00 PM.','Runs at 4:30am, noon, and 4 PM.'
    
    foreach ($string in $strings) {
        (([regex]::Matches($string, '(\d:?(?:\d{2})?(?::\d{2})?\s?(?:[a|p]m))|\d?\d?\s?(?:hour(?:\(s\))?|minutes?|noon)', @('IgnoreCase'))).Value).Trim()
    }
    
    • #69882
      Profile photo of Futureofandhra
      Futureofandhra
      Participant

      Thanks Roy I will give this a try if it works as it is simple

You must be logged in to reply to this topic.