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

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

How to extract part of string using regex

问题

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

示例字符串:

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

提取的值应该是:

Mon Aug 9 06:46:00 UTC 2021

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

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

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

英文:

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.

答案1

得分: 1

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

package main

import (
	"fmt"
	"regexp"
)

func main() {

	// 使用正则表达式提取字符串的一部分
	str := "Upgrade starting on Mon Aug 9 06:46:00 UTC 2021 with ..."

	// 使用正则表达式提取字符串 "Mon Aug 9 06:46:00 UTC 2021"
	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)

}

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

英文:

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)

}

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:

确定