I'm trying to make a simple string manipulation: getting the a file's name, without the extension. Only, string.find()
seem to have an issue with dots:
s = 'crate.png'
i, j = string.find(s, '.')
print(i, j) --> 1 1
And only with dots:
s = 'crate.png'
i, j = string.find(s, 'p')
print(i, j) --> 7 7
Is that a bug, or am I doing something wrong?
The other answers have already explained what's wrong. For completeness, if you're only interested in the file's base name you can use
string.match
. For example:string.find()
, by default, does not find strings in strings, it finds patterns in strings. More complete info can be found at the link, but here is the relevant part;To actually find the string
.
, the period needs to be escaped with a percent sign,%.
EDIT: Alternately, you can pass in some extra arguments,
find(pattern, init, plain)
which allows you to pass intrue
as a last argument and search for plain strings. That would make your statement;Do either
string.find(s, '%.')
orstring.find(s, '.', 1, true)