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

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

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

问题

我尝试使用正则表达式从生成的字符串中删除整数,但这样做不能给我所需范围内的长度(很多长度会小于最小值)。

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)

	}

}

编辑:
当我搜索问题时,我错过了详细的@icza在那个问题中的回答。这里是他的回答。

英文:

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 (
	&quot;fmt&quot;
	&quot;log&quot;
	&quot;math/rand&quot;
	&quot;regexp&quot;
	&quot;time&quot;
)

func randomString(length int) string {
	rand.Seed(time.Now().UnixNano())
	b := make([]byte, length)
	rand.Read(b)
	return fmt.Sprintf(&quot;%x&quot;, 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(&quot;[^a-zA-Z]+&quot;)
	if err != nil {
		log.Fatal(err)
	}

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

	}

}

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

答案1

得分: 3

var seededRand = rand.New(rand.NewSource(time.Now().UnixNano()))

func StringWithCharset(length int, charset string) string {
    b := make([]byte, length)
    for i := range b {
        b[i] = charset[seededRand.Intn(len(charset)-1)]
    }
    return string(b)
}

func main() {
    rangeStart := 0
    rangeEnd := 10
    offset := rangeEnd - rangeStart
    randLength := seededRand.Intn(offset) + rangeStart

    charSet := "aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ"
    randString := StringWithCharset(randLength, charSet)
}
var seededRand = rand.New(rand.NewSource(time.Now().UnixNano()))

func StringWithCharset(length int, charset string) string {
    b := make([]byte, length)
    for i := range b {
        b[i] = charset[seededRand.Intn(len(charset)-1)]
    }
    return string(b)
}

func main() {
    rangeStart := 0
    rangeEnd := 10
    offset := rangeEnd - rangeStart
    randLength := seededRand.Intn(offset) + rangeStart

    charSet := "aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ"
    randString := StringWithCharset(randLength, charSet)
}
英文:
var seededRand = rand.New(rand.NewSource(time.Now().UnixNano()))

func StringWithCharset(length int, charset string) string {
    b := make([]byte, length)
    for i := range b {
        b[i] = charset[seededRand.Intn(len(charset)-1)]
    }
    return string(b)
}

func main() {
    rangeStart := 0
    rangeEnd := 10
    offset := rangeEnd - rangeStart
    randLength := seededRand.Intn(offset) + rangeStart

    charSet := &quot;aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ&quot;
    randString := StringWithCharset(randLength, charSet)
}

答案2

得分: 1

你只需要定义你正在使用的字母表。类似以下的方式(你可以在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("这是相当随机的字符串:%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
}
英文:

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 (
  &quot;fmt&quot;
  &quot;math/rand&quot;
  &quot;strings&quot;
  &quot;time&quot;
)

func main() {

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

  var alphabet []rune = []rune(&quot;ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz&quot;)

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

}

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

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

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

  s := sb.String()
  return s
}

huangapple
  • 本文由 发表于 2022年3月16日 02:04:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/71486991.html
匿名

发表评论

匿名网友

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

确定