How to validate that a string is a proper hexadecimal value in Ruby?

!str[/\H/] will look for invalid hex values.


String#hex does not interpret the whole string as hex, it extracts from the beginning of the string up to as far as it can be interpreted as hex. With "0Z", the "0" is valid hex, so it interpreted that part. With "asfd", the "a" is valid hex, so it interpreted that part.


One method:

str.to_i(16).to_s(16) == str.downcase

Another:

str =~ /\A[a-f0-9]+\Z/i   # or simply /\A\h+\Z/ (see hirolau's answer)

About your regex, you have to use anchors (\A for begin of string and \Z for end of string) to say that you want the full string to match. Also, the + repeats the match for one or more characters.

Note that you could use ^ (begin of line) and $ (end of line), but this would allow strings like "something\n0A" to pass.

Tags:

Hex

Ruby

Regex