Home > Net >  Golang: verify that string is a valid hex string?
Golang: verify that string is a valid hex string?

Time:01-18

I have a struct:

type Name struct {
    hexID string
    age uint8
}

What is the easiest way to check that hexID field is a valid hex string? And if not - rise an error.

For example:

var n Name
n.hexID = "Hello World >)" // not a valid hex
n.hexID = "aaa12Eb9990101010101112cC" // valid hex

Or maybe there are somewhere struct tag exists?

CodePudding user response:

Iterate over the characters of the string, and check if each is a valid hex digit.

func isValidHex(s string) bool {
    for _, r := range s {
        if !(r >= '0' && r <= '9' || r >= 'a' && r <= 'f' || r >= 'A' && r <= 'F') {
            return false
        }
    }
    return true
}

Testing it:

fmt.Println(isValidHex("Hello World >)"))
fmt.Println(isValidHex("aaa12Eb9990101010101112cC"))

Output (try it on the Go Playground):

false
true

Note: you'd be tempted to use hex.DecodeString() and check the returned error: if it's nil, it's valid. But do note that this function expects that the string has even length (as it produces bytes from the hex digits, and 2 hex digits forms a byte). Not to mention that if you don't need the result (as a byte slice), this is slower and creates unnecessary garbage (for the gc to collect).

Another solution could be using big.Int.SetString():

func isValidHex(s string) bool {
    _, ok := new(big.Int).SetString(s, 16)
    return ok
}

This outputs the same, try it on the Go Playground. But this again is slower and uses memory allocations (generates garbage).

CodePudding user response:

What about this one

regexp.MatchString("[^0-9A-Fa-f]", n.hexID)

True if string contains HEX illegal characters

  • Related