Search code examples
luanumberspattern-matchingdetectionextract

Extracting number from string using lua


I have the following string as an input:

"totalling 7,525.07"

In the code below the string is indicated as "a.message"

print (string.match(a.message, "(%d+),(%d+)(%d+)(%d+).(%d+)") )

sum = (string.match(a.message, ".-(%d+). -([%d%.%,]+)") )

The code above only produces a number 7 rather than the whole number. Ideally I'm after the whole number but my code is stripping out the decimal from the figure. I've tried all sorts of different configurations but don't seem to getting anywhere.


Solution

  • You may extract the number in various ways:

    local a = "totalling  7,525.07" -- 7,525.07
    print(string.match(a, '%S+$'))  -- 7,525.07
    print(string.match(a, '%d[%d.,]*'))   -- 7,525.07
    print(string.match(a, 'totalling%s*(%S+)'))  -- 7,525.07
    print(string.match(a, 'totalling%s*(%d[,.%d]*)'))  -- 7,525.07
    print(string.match(a, '%f[%d]%d[,.%d]*%f[%D]'))  -- 7,525.07
    

    See the Lua demo

    Details

    • %S+$ - matches 1+ non-whitespace chars at the end of the string (as the number is at the end of the string, it works)
    • %d[%d.,]* - a digit followed with 0+ digits, . or , chars
    • totalling%s*(%S+) - matches totalling, 0+ whitespaces and then captures 0+ non-whitespace chars and returns the captured value
    • totalling%s*(%d[,.%d]*) - also a pattern that relies on the totalling context, but using the second pattern to capture the number
    • %f[%d]%d[,.%d]*%f[%D] - %f[%d] asserts the position between a non-digit and a digit, %d[,.%d]* matches a digit and then 0+ digits, . or , and %f[%D] fontier pattern asserts the position between a digit and a non-digit.