Search. with string.find ()

I am trying to do simple string manipulation: getting a file name without extension. Only string.find() seems to have a dot problem:

 s = 'crate.png' i, j = string.find(s, '.') print(i, j) --> 1 1 

And only with points:

 s = 'crate.png' i, j = string.find(s, 'p') print(i, j) --> 7 7 

Is this a mistake, or am I doing something wrong?

+7
source share
3 answers

string.find() does not find strings in strings by default; it finds patterns in strings. More complete information can be found here, but here is the relevant part;

"." is a wildcard that can represent any character .

To find a string . , the period must be escaped with a percent sign, %.

EDIT: alternatively, you can pass a few extra arguments, find(pattern, init, plain) , which allows you to pass true as the last argument and search for simple strings. This will make your expression;

 > i, j = string.find(s, '.', 1, true) -- plain search starting at character 1 > print(i, j) 6 6 
+14
source

Do either string.find(s, '%.') Or string.find(s, '.', 1, true)

+7
source

Other answers have already explained what is wrong. For completeness, if you are only interested in the base file name, you can use string.match . For example:

 string.match("crate.png", "(%w+)%.") --> "crate" 
+3
source

All Articles