If you insist on a loose definition of a numeric value like the one shown in the regular regex we are in trouble since lua-patterns do not support the alternation operation |
.
The suggested pattern ([+-]?%d*%.?%d+)
works actually for most cases, however, if you also want to allow cases like 42.
(as the PCRE does) it will fail.
We could try to use parenthesis and an optional extra dot that will fall off in case like this: ([+-]?%d*%.?%d+)%.?
This comes close but removes the final dot if not followed by a digit and therefore returns false positives like .12.
as .12
. *
*(Though, effectively it's the same as your RE \[+-\]?(\d+(\.\d+)?|\.\d+)
without the exponential part..
In case I would prefer a more complete RE like this: ^[+-]?((\d+(\.\d*)?)|(\.\d+))$
)
Demo code:
re = "^([+-]?%d*%.?%d+)%.?$"
v = {'123', '23.45', '.45', '-123', '-273.15', '-.45', '+516', '+9.8', '+.5', -- regular matches
'34.', '+2.', '-42.', --only matched by prolematic last optional dot
'.', '-.', '+.', ' ', '', --expected no matches
'.12.', '+.3.', '-.1.', --false positives (strictly speaking)
'+1.23.45' -- no matches
}
for i, v in ipairs(v) do
n = v:match (re)
print (n)
end
I think the first suggested option is acceptable. If even the second version still doesn't cut it I would suggest trying lrexlib, a multi-flavor regex library, or LPeg, a powerful text parsing library for Lua.