Ruby, check if there is a string in valid hexadecimal characters?

I need to check if a 4-character string is hexadecimal, I found another question that demonstrates exactly what I want to do, but this is Java: The regular expression for checking a string contains only hexadecimal characters

How can i do this?

I am reading ruby ​​documents for regular expressions, but I don't understand how to return true or false based on this match?

+7
source share
2 answers

In ruby ​​regex, \ h corresponds to a hexadecimal digit, while \ H corresponds to a non-hexadecimal digit.

So !str[/\H/] is what you are looking for.

+19
source
 if str =~ /^[0-9A-F]+$/ 

does the trick. If you want case insensitive then:

 str =~ /^[0-9A-F]+$/i 
+5
source

All Articles