sudo
sudo

Reputation: 69

lua string.find can't match "/"

Lua string.find can't find "/" in a reverse way of find, look at the following code:

c="~/abc.123" print(string.find(c,"/",-1,true))

This always returns "nil"

Upvotes: 1

Views: 911

Answers (4)

warspyking
warspyking

Reputation: 3113

Lua can't do leftwards searches, consider reversing the string first:

function Find_Leftwards(s,m,i)
    local b,f = s:reverse():find(m, i)
    return #s-f, #s-b
end

Upvotes: 1

lhf
lhf

Reputation: 72422

To find the last occurrence of /, use string.find(s,".*/"). The second return value is the position of the last /.

Upvotes: 1

Oka
Oka

Reputation: 26385

string.find cannot be used to do a leftwards search of a string. The init parameter merely sets the position from which to begin a rightwards search:

A third, optional numeric argument init specifies where to start the search; its default value is 1 and can be negative.

And an earlier note from the manual on negative indices:

Indices are allowed to be negative and are interpreted as indexing backwards, from the end of the string. Thus, the last character is at position -1, and so on.

You'll need to roll your own function which searches for an index starting from the right:

local function r_find (str, chr)
    local bchar = chr:byte(1)

    for i = #str, 1, -1 do
        if str:byte(i) == bchar then
            return i
        end
    end
end

print(r_find('~/.config/foo/bar', '/')) --> 14

Or consider using string.match to find the last section:

print(('~/.config/foo/bar'):match('/([^/]+)$')) --> 'bar'

Another option would be to simply split the string into its individual sections, and get the last section.

Upvotes: 0

Piglet
Piglet

Reputation: 28994

Please refer to the Lua reference manual. https://www.lua.org/manual/5.3/

string.find(c,"/",-1,true)

The third parameter of string.find will determin where to start the search. As you entered -1 you will start at the last character of your string and search forward. Of course you won't find anything that way.

For strings positive indices give a position from the beginning and negative indices give a position from the string's end.

Use 1 to start from the first character. Then you'll find your slash. Alternatively you could use anything <= -8

Please note that you could also write c:find("/",1,true) as a shorter version.

Upvotes: 1

Related Questions