Gxg Bbg
Gxg Bbg

Reputation: 31

Lua: match pattern till the last digit occurence

I need to match a string till the last digit occurence in Lua.

I tried .*(%d+) and .*(%d)+ patterns but they don't work

local s = "HJFverhs.1.iufbgej"
local p1 = ".*(%d+)"
local p2 = ".*(%d)+"
local s1 = s:match(p1) -- 1
local s2 = s:match(p2) -- nil

I want HJFverhs.1 to be returned

Upvotes: 2

Views: 32

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627327

Both .*(%d+) and .*(%d)+ result in the same output because .* matches any zero or more chars as many as possible, and then (%d+) captures just one last digit into Group 1, and (%d)+ captures the last digit, too (techincally, these are different patterns, but due to .* there is only one digit both (%d+) and (%d)+ can match). The string.match only returns the captured substring if there is a capturing group in the regex, and your regex contains that one capturing group.

You need

local p1 = "^.*%d"

Here,

  • ^ - start of string
  • .* - any zero or more chars as many as possible
  • %d - a digit character.

See the Lua demo.

Note the ^, start of string anchor, is not necessary here if you go on using string.match. It just explicitly says to start matching from the start of the string. In case you ever want to get consistent results with string.gmatch, you will find it helpful.

Upvotes: 1

Related Questions