gpt4 book ai didi

regex - 是否可以从 golang 中的字符串(复杂字符串)中检索子字符串

转载 作者:数据小太阳 更新时间:2023-10-29 03:08:58 25 4
gpt4 key购买 nike

我在使用正则表达式的时候遇到了一个问题,有两个问题需要解决,从简单到复杂。首先是使用正则表达式匹配字符串,然后它应该从消息中检索一些子字符串。

就像我有一个字符串,它是

“当前聊天室:今天吃什么?(本帖由Sharon编辑,Leon于2018-11-10 21:00:00发送)”

"在当前聊天室:Hey mate,你喜欢golang吗?(此消息由Leon编辑,消息来自Mike于2018-01-10 10:00:59发送)"

在上面的消息中,有些部分不会改变例如“在当前聊天室:”和“此消息由...编辑,消息在...从...发送”

当我遇到这种消息时,这被认为是“编辑通知”我需要过滤所有使用该结构编译的消息。

我写的是

var testRgx = regexp.MustCompile(`^In current chatting room: .* \(This message is edited by .*, the message is sent on .* from .*\)$`)

我知道这有点笨,但至少可以工作

当我运行它时,结果显示它是正确的。

sample := "In current chatting room: what do you eat for today? I input some shit (sdfhjskdfjksljhfdsjkdf) can you detect this? (This message is edited by Sharon, the message is sent on 2018-11-10 21:00:00 from Leon)"
fmt.Println(testRgx.MatchString(sample ))

到现在我觉得还好

第二步是检索内容、编辑、时间和原发件人。

我所做的是替换第一部分,即“在当前聊天室中:”然后字符串更改为

changedString := "what do you eat for today? I input some shit (sdfhjskdfjksljhfdsjkdf) can you detect this? (This message is edited by Sharon, the message is sent on 2018-11-10 21:00:00 from Leon)"

从字符串的末尾开始,我在最后一个 from 之后截断了字符串,这样我就可以取出“Leon”。

//after cut after from
cutString := "what do you eat for today? I input some shit (sdfhjskdfjksljhfdsjkdf) can you detect this? (This message is edited by Sharon, the message is sent on 2018-11-10 21:00:00 "

然后把最后一个on之后的字符串剪下来得到时间。

//after cut after on
cutString := "what do you eat for today? I input some shit (sdfhjskdfjksljhfdsjkdf) can you detect this? (This message is edited by Sharon, the message is sent "

然后最后一步是取回编辑器。

我认为这种方法很愚蠢,我已经搜索了一些示例,例如使用正则表达式检索组件 Golang: extract data with Regex

但这是一个有点复杂的案例,我认为我编写的检索组件的方法非常丑陋。

请问有没有办法直接使用正则表达式来获取组件?

对于通知消息,

“在当前聊天室:”不会改变,编辑消息的组成部分会改变,括号内的内容只会改变编辑者(Sharon),时间(2018-11-10 21:00:00)和发件人(Leon),括号中的其他部分不会像

(此消息由xxxxx编辑,消息由xxxx于xxxx发送)

最佳答案

让我尝试理解您的问题,在给定的输入字符串中,您想要查找编辑者和发件人姓名,还想提取日期和时间。

作为开始,你可以有两个正则表达式,一个用于匹配名称,另一个用于日期和时间,你可以这样做

namesRegex, _ := regexp.Compile("by\\s(.*?),(.*?)\\s*from\\s*(.*?)\\)")
dateTimeRegex, _ := regexp.Compile("(\\d{4})-(\\d{2})-(\\d{2}) (\\d{2}):(\\d{2}):(\\d{2})")
input := "In current chatting room: what do you eat for today? (This message is edited by Sharon, the message is sent on 2018-11-10 21:00:00 from Leon)"
if namesRegex.MatchString(input) {
res := namesRegex.FindStringSubmatch(input)
fmt.Println("Edited by = ", strings.TrimSpace(res[1]))
fmt.Println("From = ", strings.TrimSpace(res[3]))
}
if dateTimeRegex.MatchString(input) {
res := dateTimeRegex.FindAllString(input, 1)
fmt.Println(res[0])
}

输出:

由 = Sharon 编辑

来自 = 莱昂

2018-11-10 21:00:00

关于regex - 是否可以从 golang 中的字符串(复杂字符串)中检索子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55718920/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com