3

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

  • 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 http://stackoverflow.com/questions/4098086/to-use-or-not-to-use-regular-expressions/4098123#4098123 and heed its wisdom. –  Mar 31 '11 at 18:54

2 Answers2

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.

glenn jackman
  • 238,783
  • 38
  • 220
  • 352
Staffan Nöteberg
  • 4,095
  • 1
  • 19
  • 17
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}
glenn jackman
  • 238,783
  • 38
  • 220
  • 352