Search code examples
goregexp-replace

find number in string and replace it with a string from a dictionary in golang


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.


Solution

  • 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])
          }