12

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?

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
user2141781
  • 121
  • 1
  • 1
  • 4
  • See [How to string.find the square bracket character in lua](http://stackoverflow.com/questions/6077423/how-to-string-find-the-square-bracket-character-in-lua). Although it refers to a different special character, the solution is the same. – finnw Mar 07 '13 at 11:19

3 Answers3

24

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;

The '.' represents a wildcard character, which can represent any character.

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 in true as a last argument and search for plain strings. That would make your statement;

> i, j = string.find(s, '.', 1, true)   -- plain search starting at character 1
> print(i, j) 
6 6
Joachim Isaksson
  • 176,943
  • 25
  • 281
  • 294
  • 1
    -1; The escape character for Lua [patterns](http://www.lua.org/manual/5.2/manual.html#6.4.1) is `%`, not `\ `. Trying to use a backslash will probably give you an "invalid escape sequence" error. – hugomg Mar 07 '13 at 03:32
  • @missingno You're of course correct, I mixed up the escape character for escape sequences and patterns. Fixed the answer. – Joachim Isaksson Mar 07 '13 at 05:42
10

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

Egor Skriptunoff
  • 23,359
  • 2
  • 34
  • 64
5

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.match("crate.png", "(%w+)%.")  --> "crate"
greatwolf
  • 20,287
  • 13
  • 71
  • 105