Finding a string in a string via regex in Go

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

Finding a string in a string via regex in Go

问题

我正在尝试编写一个正则表达式,以返回一个字符串给我。

我有一个完整的字符串,像这样:

@badges=moderator/1,premium/1;color=#00FF80;display-name=gempir;emotes=;id=d0358df2-f0a1-4600-910e-515ec52b1baa;mod=1;room-id=99659894;sent-ts=1489250823035;subscriber=0;tmi-sent-ts=1489250823211;turbo=0;user-id=77829817;user-type=mod :gempir!gempir@gempir.tmi.twitch.tv PRIVMSG #gempbot :!status

我想要找到命令"PRIVMSG",因为有类似的完整字符串有不同的命令。像这样:

@ban-duration=20;ban-reason=Banned\slink;room-id=11148817;target-user-id=78424343 :tmi.twitch.tv CLEARCHAT

如果你感兴趣,这些是带有ircv3标签的twitch irc消息。

现在我有这个正则表达式:

^@(.*)\s:(.*?)tmi.twitch.tv\s

我该如何在Go中使用这个正则表达式或类似的表达式来找到我要找的字符串?

我想避免一次又一次地拆分,因为这似乎有点不合理和难以阅读。我认为一个正则表达式可以解决我所有的问题。

英文:

I'm trying to write a regex that returns a string to me

I have a full string like this:

@badges=moderator/1,premium/1;color=#00FF80;display-name=gempir;emotes=;id=d0358df2-f0a1-4600-910e-515ec52b1baa;mod=1;room-id=99659894;sent-ts=1489250823035;subscriber=0;tmi-sent-ts=1489250823211;turbo=0;user-id=77829817;user-type=mod :gempir!gempir@gempir.tmi.twitch.tv PRIVMSG #gempbot :!status

and what to find the command "PRIVMSG" because there are similar full strings that have different commands. Like this:

@ban-duration=20;ban-reason=Banned\slink;room-id=11148817;target-user-id=78424343 :tmi.twitch.tv CLEARCHAT

If you are interested these are twitch irc messages with ircv3 tags

now I have this regex:

^@(.*)\s:(.*?)tmi.twitch.tv\s

how do I use the regex or a similar one in Go to find the string im looking for?

I wanted to avoid splitting again and again because it seems kinda unreasonable and hard to read. I think a regex can fix all my problems.

答案1

得分: 0

以下的正则表达式应该可以实现...

(?<=twitch.tv\s)\w+(?=\s#)

参见**正则表达式演示**

英文:

The following regex should do it ...

(?&lt;=twitch.tv\s)\w+(?=\s#)

see regex demo

答案2

得分: 0

只是为了不锚定在网址上(可能会有所更改),我更喜欢这种形式:

([A-Z]+)(\s#.+)?$
英文:

Just not to be anchored to the web-address (which can be changed some time) i'd prefer this kind:

([A-Z]+)(\s#.+)?$

huangapple
  • 本文由 发表于 2017年3月12日 01:03:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/42738066.html
匿名

发表评论

匿名网友

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

确定