In Golang How to generate a random string of random length within range without integers

Issue

I tried to remove the integer from the generated string with regex but this will not give me the length within the range required( many will be less than the minimum )

package main

import (
    "fmt"
    "log"
    "math/rand"
    "regexp"
    "time"
)

func randomString(length int) string {
    rand.Seed(time.Now().UnixNano())
    b := make([]byte, length)
    rand.Read(b)
    return fmt.Sprintf("%x", b)[:length]
}
func randomLength(minL, maxL int) int {
    rand.Seed(time.Now().UnixNano())

    return rand.Intn(maxL-minL) + minL
}

func main() {
    reg, err := regexp.Compile("[^a-zA-Z]+")
    if err != nil {
        log.Fatal(err)
    }

    for i := 0; i < 10; i++ {
        processedString := reg.ReplaceAllString(randomString(randomLength(8, 16)), "")
        println(processedString)

    }

}

Edit:
when I searched for the question I missed detailed @icza answer in that question.

Solution

You just need to define the alphabet that you’re using. Something like the following (You can fiddle with it here in the Go Playground).

package main

import (
  "fmt"
  "math/rand"
  "strings"
  "time"
)

func main() {

  rand.Seed(time.Now().UnixNano())

  var alphabet []rune = []rune("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz")

  rs := randomString(20, alphabet)
  fmt.Printf("This is pretty random: %s\n", rs)

}

func randomString(n int, alphabet []rune) string {

  alphabetSize := len(alphabet)
  var sb strings.Builder

  for i := 0; i < n; i++ {
    ch := alphabet[rand.Intn(alphabetSize)]
    sb.WriteRune(ch)
  }

  s := sb.String()
  return s
}

Answered By – Nicholas Carey

Answer Checked By – Candace Johnson (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.