我在使用正则表达式时遇到了一个问题,需要解决两个问题,从简单到复杂。首先是使用正则表达式来匹配字符串,然后从消息中检索一些子字符串。
就像我有一根绳子,是
在现在的聊天室:你今天吃什么?(这条消息由莎伦编辑,2018-11-10 :00从里昂发来)
在现在的聊天室里:嘿,伙计,你喜欢高朗吗?(这条消息由里昂编辑,2018-01- 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)"从字符串的末端开始,我在最后一个字符串之后剪断了字符串,这样我就可以把"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 "然后在最后一次打开后剪断绳子以获得时间。
//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 "最后一步是取出编辑器。
我认为这个方法很愚蠢,我搜索了一些示例,比如使用regexp Golang: extract data with Regex检索组件。
但是这是一个有点复杂的情况,我认为检索我编写的组件的方法很难看。
请问是否有一种直接使用正则表达式来获取组件的方法?
关于通知信息,
在当前的聊天室:“不会更改,编辑后的消息组件会改变,而括号内的内容只会更改编辑器(沙龙)、时间(2018-11-10 :00:00)和发件人(Leon),括号中的其他部分不会改变。”
(此消息由xxxxx编辑,消息从xxxx发送到xxxx)
发布于 2019-04-17 03:13:22
让我试着理解你的问题,在给定的输入字符串中,你想要找到编辑器和发送者的名字,也想要提取日期和时间。
首先,您可以有两个正则表达式-一个用于匹配名称,另一个用于日期和时间,您可以这样做
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
From = Leon
2018-11-10 21:00
发布于 2019-04-17 02:33:33
我不能发表评论,所以我不得不把这个放在这里.你研究过regex抓捕小组吗?
eg How to get capturing group functionality in Golang regular expressions?
https://stackoverflow.com/questions/55718920
复制相似问题