check if valid hexadecimal code?

C

Craig Demyanovich

[Note: parts of this message were removed to make it a legal post.]

How would you check if a string is a valid hexadecimal code?

irb(main):007:0> hex_pattern = /^[[:xdigit:]]+$/
=> /^[[:xdigit:]]+$/
irb(main):008:0> hex_pattern === "0123456789ABCDEF"
=> true
irb(main):009:0> hex_pattern === "Chunky Bacon"
=> false


I wonder if you should use /\A[[:xdigit:]]+\z/ to match the beginning and
end of the string instead of the beginning and end of the line.

Another options is to use String#hex method and check the return value,
though I find it weird that it returns 0 on error, since "0x0".hex also
returns 0

Regards,
Craig
 
C

Chealsea S.

I tried "hex_pattern" with a string like "asdbgg" and it does not
produce an error, even though "g" isn't A-F 0-9.

I should specify that I'm trying to build a hexadecimal color checker.
I tried the folllowing code but it doesn't work:

def ishex(hexcolor)
if (hexcolor.to_s.length == 6) == false
then
false
elsif hexcolor.hex == 0
false
else
true
end
end



Thanks for any help.



Avdi said:
How would you check if a string is a valid hexadecimal code?

irb(main):007:0> hex_pattern = /^[[:xdigit:]]+$/
=> /^[[:xdigit:]]+$/
irb(main):008:0> hex_pattern === "0123456789ABCDEF"
=> true
irb(main):009:0> hex_pattern === "Chunky Bacon"
=> false


--
Avdi

Home: http://avdi.org
Developer Blog: http://avdi.org/devblog/
Twitter: http://twitter.com/avdi
Journal: http://avdi.livejournal.com
 
B

Brian Candler

Craig said:
Another options is to use String#hex method and check the return value,
though I find it weird that it returns 0 on error, since "0x0".hex also
returns 0

It just stops at the first non-hex character.

irb(main):002:0> "123zzz".hex
=> 291

But you could do this:

irb(main):003:0> str="123"
=> "123"
irb(main):004:0> Integer("0x#{str}")
=> 291
irb(main):005:0> str="123zzz"
=> "123zzz"
irb(main):006:0> Integer("0x#{str}")
ArgumentError: invalid value for Integer: "0x123zzz"
from (irb):6:in `Integer'
from (irb):6
from :0
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,197
Messages
2,571,040
Members
47,634
Latest member
RonnyBoelk

Latest Threads

Top