Peter.k
Peter.k

Reputation: 1548

How to extract numbers from a string in Lua?

I can't find how to do a simple regex in Lua. In every normal language it is:

string:match( "($1,000)", "[\d]+")

It returns: 1000 (if you concatenate matches).

I thought string.match( "($1,000)", "%d+") ) will do the job but it returns nil or 1.

I don't understand it.

Upvotes: 2

Views: 4544

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626728

You may remove all matches that follow the %D+ (1 or more non-digit chars) pattern with string.gsub:

s = "($1,000)"
res, _ = s:gsub("%D+", "")
print(res)
-- => 1000

See the Lua demo

Upvotes: 4

Related Questions