Regex number of occurrences help

local inputStr = "1234" 
inputStr = inputStr:match("^%d{0,3}") 
print(inputStr)

Why does it return nil, and not “123”? Thanks!

Lua does not support RegEx, you might be better off learning Lua’s nightmarish patterns or finding a RegEx library (I myself have not found any)

This one should work though:

local inputStr = "1234" 
inputStr = inputStr:match("^%d%d?%d?")
print(inputStr)

FYI; RegEx by itself is like 20x larger than the entirety of Lua’s source code, which is why it is not embedded into lua.

Here’s my full code: inputStr = inputStr:match("^%-?(%d{0,4}?)%.?(%d{0,3}?)")
What I’m doing here, is I want an optional minus, 4 digits before the decimal point, an optional decimal point, and 3 digits after the decimal point if I have a decimal point.

This inputStr = inputStr:match("^%-?%d?%d?%d?%d?%.?%d?%d?%d?") doesn’t work because it allows for a 7 digit number, which I want to avoid. Is there a way to do this? Thanks!

local inputStr = "1234.56789"  -- Example input
local pattern = "^(%-?)(%d%d?%d?%d?)%.?(%d?%d?%d?)"
local sign, beforeDecimal, afterDecimal = inputStr:match(pattern)

local result = sign .. beforeDecimal
if afterDecimal ~= "" then
	result = result .. "." .. afterDecimal
end

print(result)

?

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.