Rahul Choudhary
Rahul Choudhary

Reputation: 31

Lua regex to find a numeral in a string

what's the right regular expression to find a numeral in a string, in Lua? Due to the way parentheses are used in lua regular expressions, it seems hard to correctly match the decimal point and the digits after it.

The workaround in the test code below works for my script's immediate needs, but accepts patterns like +1.23.45 as well.

--[+-]?(\d+(\.\d+)?|\.\d+)([eE][+-]?\d+)?  std regex for a numeral

s = "+1.23"
re = "([+-]?%d+[%.%d+]*)"
n = s:match (re)
print (n)

Upvotes: 2

Views: 1342

Answers (1)

wp78de
wp78de

Reputation: 18950

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.

Upvotes: 2

Related Questions