This topic contains 4 replies, has 4 voices, and was last updated by  Jeff Drumm 6 years, 3 months ago.

Test value to see if numeric

  • I want to be able to test if a value received in a field is a numeric value. The issue is that we are receiving messages from a customer where the value can’t be guaranteed to be a number. I want to check to see if it is a number. If it is, then I can run a different check to normalize it as a date. But if it’s non-numeric text, I need to clear the value and move on.

    -Robert James,
    Interface Analyst,
    GetWellNetwork, Inc.

    Hi Robert,

    Check out the global type function to determine the type of the field:

    Do you think this addresses your need?

    Casey Trauer,
    Customer Solutions Developer

    Casey Trauer,
    Director, Client Education

    Hi Robert,

    You’ll likely be best off using a pattern match function if you’re evaluating a node in a HL7 message. The problem with the type() function is that it normally returns ‘userdata’ as the type when used against a VMD-parsed HL7 message, and calling nodeValue() before type() will return ‘string’.

    But you can do this:

       -- verify that PID-7 is a positive integer
       if Msg.PID[7]:S():match("^%d+$") then
          -- value is numeric, do the number thing
          -- value is not numeric, do something else

    The pattern “^$d+$” represents the beginning of the string (^) followed by one or more digits (%d+), followed by the end of the string ($). The problem with this pattern is that it does not handle negative or fractional decimal numbers. The pattern can be modified to accommodate those, but the Lua built-in pattern matching functionality is somewhat less than awesome and such modifications may allow some strange values as numbers. If you’re running 5.6.16 or later, though, you have full regular expression matching available with the rxmatch() and rxsub() functions.

    Jeff Drumm ◊ VP and COO ◊ HICG, LLC. ◊

    Incidentally the type function won’t work because the HL7 tree is a tree of strings. Well actually ‘node trees’ so the type would be reported as ‘userdata’.

    Jeff’s solution should work.

    Another idea would be to use this function:

    function IsNumber(Node)
    local S = tostring(Node);
    return tostring(tonumber(S)) == S;

    if IsNumber(Msg.PID[3][1]) then

    I tried it out and it seems to work as expected – screen shot attached.

    You must be logged in to view attached files.

    Eliot’s solution also neatly handles negative and decimal values.

    If you’re checking for a date value that may contain non-numeric characters, though, you may also want to check that it’s actually a valid date. There are a few functions on that might prove useful in that case.

    Jeff Drumm ◊ VP and COO ◊ HICG, LLC. ◊

You must be logged in to reply to this topic.