3

Is there away to write a Tcl regex to verify that a string is a hex number that is even?

1
  • A hex number is easy. Checking eveness is still possible (actually, still easy) because the last digit determines that - but in general, you should read stackoverflow.com/questions/4098086/… and heed its wisdom.
    – user395760
    Mar 31, 2011 at 18:54

2 Answers 2

4

This tcl code will do the work:

if {[regexp -linestop -nocase {^[\da-f]*[02468ace]$} $input]} {
    # Success
} else {
    # Fail
}

Note that a, c and e are also even numbers and that you need -nocase to match a-f as well as A-F.

2
  • I added braces around the if condition to delay evaluation Mar 31, 2011 at 21:07
  • You probably don't need -linestop; the default “match the whole string” behavior is suitable for this sort of task. Apr 2, 2011 at 8:06
4

Does it need to be a regex?

proc is_even {n} {expr {($n & 1) == 0}}

if {[is_even 0xdeadbeef]} {puts even} else {puts odd}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.