在 switch case 中使用正则表达式

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

Regular expression at switch case

问题

我需要编写一个简单的Telegram机器人。除了一个问题,其他都正常工作。当我输入命令\任务#1时,它应该给我提供相应的链接,\任务#2应该给我提供相应的链接,以此类推。如何更好地安排这个问题,或者如何为正则表达式制作switch case?


import (
	"log"
	"strconv"
	"github.com/go-telegram-bot-api/telegram-bot-api"
)

func main() {
	bot, err := tgbotapi.NewBotAPI("")
	tasks := [...]string{"Ansible assignment", "Bash script"}
	links := [...]string{"https://github.com/task1", "https://github.com/task2"}

	if err != nil {
		log.Panic(err)
	}

	bot.Debug = true

	log.Printf("Authorized on account %s", bot.Self.UserName)

	u := tgbotapi.NewUpdate(0)
	u.Timeout = 60

	updates, err := bot.GetUpdatesChan(u)

	for update := range updates {
		if update.Message == nil { // ignore any non-Message Updates
			continue
		}
		log.Printf("[%s] %s", update.Message.From.UserName, update.Message.Text)

		if update.Message.IsCommand() {
			msg := tgbotapi.NewMessage(update.Message.Chat.ID, "")
			switch update.Message.Command() {
			case "help":
				msg.Text = "type /sayhi or /status."
			case "homerep":
				msg.Text = "https://github.com/ :)"
			case "tasks":
				msg.ParseMode = "html"
				msg.Text = "The list of completed tasks:\n"
				for i := 0; i < len(tasks); i++ {
					msg.Text = msg.Text + strconv.Itoa(i+1) + ". " + tasks[i] + "  -  " + "<a href='" + links[i] + "'><b>link</b></a>" + "\n"
				}
			case "task#":
				msg.ParseMode = "html"
				msg.Text = "This is test"
			default:
				msg.Text = "I don't know that command"
			}
			bot.Send(msg)
		}
	}
}
英文:

I need to write a simple telegram bot.
Everything is working except 1 thing. When I'm writing command \task#1 - it should give me the link for it, \task#2 - should give the link to task2, etc.
How to arrange this better or how to make switch case for regular expression?


import (
	&quot;log&quot;
    &quot;strconv&quot;
//     &quot;regexp&quot;
	&quot;github.com/go-telegram-bot-api/telegram-bot-api&quot;
)

func main() {
	bot, err := tgbotapi.NewBotAPI(&quot;&quot;)
	tasks := [...]string{&quot;Ansible assignment&quot;, &quot;Bash script&quot;}
	links := [...]string{&quot;https://github.com/task1&quot;, &quot;https://github.com/task2&quot;}
// 	var currentTask = regexp.MustCompile(`^task#.`)

	if err != nil {
		log.Panic(err)
	}

	bot.Debug = true

	log.Printf(&quot;Authorized on account %s&quot;, bot.Self.UserName)

	u := tgbotapi.NewUpdate(0)
	u.Timeout = 60

	updates, err := bot.GetUpdatesChan(u)

	for update := range updates {
		if update.Message == nil { // ignore any non-Message Updates
			continue
		}
		log.Printf(&quot;[%s] %s&quot;, update.Message.From.UserName, update.Message.Text)


if update.Message.IsCommand() {
			msg := tgbotapi.NewMessage(update.Message.Chat.ID, &quot;&quot;)
			switch update.Message.Command() {
			case &quot;help&quot;:
				msg.Text = &quot;type /sayhi or /status.&quot;
			case &quot;homerep&quot;:
				msg.Text = &quot;https://github.com/ :)&quot;
			case &quot;tasks&quot;:
			    msg.ParseMode = &quot;html&quot;
			    msg.Text = &quot;The list of completed tasks:\n&quot;
			    for i := 0; i &lt; len(tasks); i++ {
       				msg.Text =  msg.Text + strconv.Itoa(i+1) + &quot;. &quot; + tasks[i] +  &quot;  -  &quot; + &quot;&lt;a href=&#39;&quot;+links[i] +&quot;&#39;&gt; &lt;b&gt;link&lt;/b&gt;&lt;/a&gt;&quot; + &quot;\n&quot;
                }
			case update.Message.Command == &quot;^task#.&quot;:
				msg.ParseMode = &quot;html&quot;
				msg.Text = &quot;This is test&quot;
			default:
				msg.Text = &quot;I don&#39;t know that command&quot;
			}
			bot.Send(msg)
		}
}
}```


</details>


# 答案1
**得分**: 4

将正则表达式编译并分配给一个包级变量:

```go
var commandPat = regexp.MustCompile(`^task#.`)

修改 switch 语句以使用表达式。使用 MatchString 来进行正则表达式匹配:

switch cmd := update.Message.Command(); { // 注意这一行上的分号!
case cmd == "help":
   ...
case cmd == "homerep":
   ...
case cmd == "tasks":
   ...
case commandPat.MatchString(cmd):
   ...
英文:

Compile the regular expression and assign it to a package-level variable:

var commandPat = regexp.MustCompile(`^task#.`)

Modify the switch to use expressions. Use MatchString for the regular expression:

switch cmd := update.Message.Command(); { // note the ; on this line!
case cmd == &quot;help&quot;:
   ...
case cmd == &quot;homerep&quot;:
   ...
case cmd == &quot;tasks&quot;:
   ...
case commandPat.MatchString(cmd):
   ...

huangapple
  • 本文由 发表于 2021年6月18日 06:01:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/68027004.html
匿名

发表评论

匿名网友

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

确定