String.gsub() to extract last word in string

150 Views Asked by At

I have a string where the words within are separated by periods, what would be the best way for returning the last word? My guess would be to use string.gsub, but i'm having a hard time figuring out the correct syntax

here's an example:

str = "These.Are.A.Few.Words.But.I_only_want_this"

Desired output would be:

I_only_want_this

Note that i don't need to treat any magical characters as such, they can stay in the string no problems

1

There are 1 best solutions below

4
Oka On BEST ANSWER

Try:

str:gsub('.*%.', '')

.* - Match zero or more (*) of any character (.), taking the longest sequence possible.
%. - Match a literal . character.

Example:

Lua 5.4.6  Copyright (C) 1994-2023 Lua.org, PUC-Rio
> str = "These.Are.A.Few.Words.But.I_only_want_this"
> str:gsub('.*%.', '')
I_only_want_this    1