Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby, check if string is all valid hex characters?

Tags:

ruby

I have to check if a 4 character string is all valid hex, I found another question which demonstrates exactly what I want to do but it's Java: Regex to check string contains only Hex characters

How can I accomplish this?

I read the ruby docs for Regular expressions, but I don't understand how to return a true or false based on this match?

like image 428
JP Silvashy Avatar asked Jan 31 '12 06:01

JP Silvashy


2 Answers

In ruby regex \h matches a hex digit and \H matches a non-hex digit.

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

like image 181
pguardiario Avatar answered Sep 22 '22 17:09

pguardiario


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

does the trick. If you want case insensitive then:

str =~ /^[0-9A-F]+$/i
like image 39
Jakub Hampl Avatar answered Sep 24 '22 17:09

Jakub Hampl