如何使用正则表达式提取字符串的一部分

huangapple go评论99阅读模式
英文:

How to extract part of string using regex

问题

我正在尝试提取字符串的日期时间戳的一部分。

示例字符串:

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

提取的值应该是:

  1. Mon Aug 9 06:46:00 UTC 2021

我尝试使用以下正则表达式提取时间戳:

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

如何提取出日期、月份和年份呢?

英文:

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

Example string:

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

Extracted values should be:

  1. Mon Aug 9 06:46:00 UTC 2021

I tried applying the following regex to extract the timestamp:

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

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

答案1

得分: 1

使用正则表达式从原始字符串中提取字符串的一部分,以下是完整的代码

  1. package main
  2. import (
  3. "fmt"
  4. "regexp"
  5. )
  6. func main() {
  7. // 使用正则表达式提取字符串的一部分
  8. str := "Upgrade starting on Mon Aug 9 06:46:00 UTC 2021 with ..."
  9. // 使用正则表达式提取字符串 "Mon Aug 9 06:46:00 UTC 2021"
  10. 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}`)
  11. t := re.FindString(str)
  12. fmt.Println(t)
  13. }

请注意,这是一个使用Go语言编写的示例代码,用于从原始字符串中提取特定格式的日期时间字符串。

英文:

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

  1. package main
  2. import (
  3. "fmt"
  4. "regexp"
  5. )
  6. func main() {
  7. // extract part of string using regex
  8. str := "Upgrade starting on Mon Aug 9 06:46:00 UTC 2021 with ..."
  9. // extract string "Mon Aug 9 06:46:00 UTC 2021" using regex
  10. 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}`)
  11. t := re.FindString(str)
  12. fmt.Println(t)
  13. }

huangapple
  • 本文由 发表于 2021年11月19日 16:30:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/70031892.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定