英文:
find number in string and replace it with a string from a dictionary in golang
问题
我是你的中文翻译助手,以下是你要翻译的内容:
我对Golang还不熟悉,但我有一个需要使用Golang的项目。
我的问题是:我有一个变量输出,其中包含一些数字。这些数字代表一个命名实例。
我想要做的是:检查输出(alertmap)中的数字,并将找到的数字(num_var)与我创建的字典进行比较。如果找到匹配项,则将数字(num_var)替换为字典中的字符串(value),并放入(alertmap)中。
我有一个名为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 := range alertmap"之后插入一个if语句,以检查键(key,例如my/123456/secret/salon)中是否有数字,然后用字典中匹配的字符串替换该数字。键将变为my/project_data/secret/salon(这是我想要作为键发送的内容)。
任何帮助将不胜感激。
英文:
I am new to Golang; but I have a project that require me to work with Golang.
My Problem: I have an output coming from a variable and that output contains some numbers. those number represent a named instance.
What I am trying to do: To check the output (alertmap) for number and check the number (num_var) found against a dictionary I have created. If a match is found; replace the number (num_var) with the string (value)from the dictionary in the (alertmap).
I have a variable called alertmap that has a key and a value.
The key is what I want to change
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")
}
what I want to do is insert an if statemnet after "for key, value := range alertmap" to check if key(my/123456/secret/salon for example) has a number in it then replace that number with the string that match from the dictionary. key will the be my/project_data/secret/salon (this is what I want sent as key).
Any help will be appreciated.
答案1
得分: 0
re := regexp.MustCompile("[0-9]+")
func alertme() {
for key, value := range alertmap {
my_alert += fmt.Sprintln("\n", key, "是", value.usage, ",并且在", value.expireComputed, "天后过期")
}
// 查找要替换的值并转换为整数
dictKey, _ := strconv.Atoi(re.FindString(key))
// 替换值
replacedKey := re.ReplaceAllString(key, my_dicts[dictKey])
}
希望这个翻译对你有帮助!如果你还有其他问题,请随时提问。
英文:
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])
}
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论