首页 > 文章列表 > 使用Golang字典从字符串中查找数字并进行替换

使用Golang字典从字符串中查找数字并进行替换

156 2024-04-23
问题内容

我是 golang 新手;但我有一个项目需要我使用 golang。

我的问题:我有一个来自变量的输出,并且该输出包含一些数字。这些数字代表一个命名实例。

我想要做什么:检查数字的输出(alertmap)并检查根据我创建的字典找到的数字(num_var)。如果找到匹配项;将数字 (num_var) 替换为 (alertmap) 中字典中的字符串 (value)。

我有一个名为alertmap的变量,它有一个键和一个值。 关键是我要改什么

package main

import (
        "bytes"
        "context"
        "encoding/json"
        "fmt"
        "log"
        "math"
        "net/http"
        "os"
        "strconv"
        "time"
        "errors"
        "regexp"
        "strings"
)


my_dicts = {
123456: "project_data"
2345671: "project_dev-1"
}

func alertme ()
     for key, value := range alertmap
           my_alert += fmt.Sprintln("n", key, "is a", value.usage, "and Expires in:", value.expireComputed, "days")
                }

我想要做的是在“for key, value := rangealertmap”之后插入一个 if statemnet 来检查键(例如 my/123456/secret/salon)中是否有一个数字,然后将该数字替换为从字典中匹配的字符串。密钥将是 my/project_data/secret/salon (这是我想要作为密钥发送的内容)。 任何帮助将不胜感激。


正确答案


re := regexp.MustCompile("[0-9]+")

func alertme ()
     for key, value := range alertmap {
           my_alert += fmt.Sprintln("n", key, "is a", value.usage, "and Expires in:", value.expireComputed, "days")
                }
           // Find value to replace and convert to int
           dictKey, _ := strconv.Atoi(re.FindString(key))
           // Replace value 
           replacedKey := re.ReplaceAllString(key, my_dicts[dictKey])
      }