lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]



On 25-Jan-06, at 2:17 PM, Brian Weed wrote:

Is there a library function for a reverse find

Sadly, no.

, or do I have to do it manually as in:

-- untested
i = 0
do
   i = i - 1
   p = string.find(s, ".", i, true)
while (p == nil and i ~= -string.len(s))

(I'm searching for the file extension, and there may be other dots in the filename)

A better way:

  local _, _, extension = string.find(s, ".*%.(.*)")

or in 5.1

  local extension = s:match".*%.(.*)"

Note that you have to %-escape the '.', since an unescaped '.' in a pattern means "match anything"

Explanation: .* will match the longest sequence which makes the rest of the match possible. Since the rest of the match matches anything which starts with a '.', the longest prefix which makes that possible will end just before the last '.'.

In the case of filepaths, this is probably not particularly expensive. But on the whole, it would be nice to have a reverse find; it is probably more useful than string.reverse. (Of course, you could use string.reverse to do a reverse find but it's not going to speed things up because it copies the whole string.)