Skip to content

Instantly share code, notes, and snippets.

@iyashjayesh
Created March 15, 2023 17:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iyashjayesh/58c2460cf244306b105be2b44efe3c16 to your computer and use it in GitHub Desktop.
Save iyashjayesh/58c2460cf244306b105be2b44efe3c16 to your computer and use it in GitHub Desktop.
Convert (b,mb,gb,tb,pb) Memory data to kb using regex in Golang
package main
import (
"fmt"
"regexp"
"strconv"
"strings"
)
func main() {
sizes := []string{"12pb", "12p", "12tb", "12t", "12gb", "12g", "12mb", "12m", "12kb", "12k", "12222b", "12", "12PB", "12P", "12TB", "12T", "12GB", "12G", "12MB", "12M", "12KB", "12K", "12222B", "12"}
// pb = petabytes
// p = petabytes
// tb = terabytes
// t = terabytes
// gb = gigabytes
// g = gigabytes
// mb = megabytes
// m = megabytes
// kb = kilobytes
// k = kilobytes
// b = bytes
for _, size := range sizes {
regKb, err := regexToKB(size)
if err != nil {
fmt.Printf("error converting %s to KB: %v\n", size, err)
} else {
fmt.Printf("regex- %s = %d KB\n", size, regKb)
}
}
}
func regexToKB(size string) (int64, error) {
regex := regexp.MustCompile(`^(\d+)([bkmgtp]?b?)$`)
match := regex.FindStringSubmatch(strings.ToLower(size))
if match == nil {
return 0, fmt.Errorf("invalid size format: %s", size)
}
num, err := strconv.ParseInt(match[1], 10, 64)
if err != nil {
return 0, fmt.Errorf("invalid size format: %s", size)
}
var kb int64
switch strings.TrimSuffix(match[2], "b") {
case "":
return num, nil
case "k":
kb = 1024
case "m":
kb = 1024 * 1024
case "g":
kb = 1024 * 1024 * 1024
case "t":
kb = 1024 * 1024 * 1024 * 1024
case "p":
kb = 1024 * 1024 * 1024 * 1024 * 1024
default:
return 0, fmt.Errorf("invalid size format: %s", size)
}
return num * kb / 1024, nil
}
@iyashjayesh
Copy link
Author

iyashjayesh commented Mar 15, 2023

regex := regexp.MustCompile(`^(\d+)([bkmgtp]?b?)$`)

^ matches the start of the string.
(\d+) matches one or more digits and captures them in a group.
([bkmgtp]?b?) matches a letter
$ matches the end of the string.

I hope this helps you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment