Home > other >  How to extract part of string using regex
How to extract part of string using regex

Time:11-20

I am trying to extract a part of a string as date-timestamp.

Example string:

Upgrade starting on Mon Aug 9 06:46:00 UTC 2021 with ...

Extracted values should be:

Mon Aug 9 06:46:00 UTC 2021

I tried applying the following regex to extract the timestamp:

(\d{2}:\d{2}:\d{2})

How can I extract the day month and year as well.

CodePudding user response:

Use regex to extract part of string from raw string, the following is the whole code

package main

import (
    "fmt"
    "regexp"
)

func main() {

    // extract part of string using regex
    str := "Upgrade starting on Mon Aug 9 06:46:00 UTC 2021 with ..."

    // extract string "Mon Aug 9 06:46:00 UTC 2021" using regex
    re := regexp.MustCompile(`(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) \d{1,2} \d{2}:\d{2}:\d{2} (\S{3}) \d{4}`)
    t := re.FindString(str)
    fmt.Println(t)

}

  • Related