Finding '.' with string.find()

那年仲夏 提交于 2019-12-01 00:33:31

问题


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?


回答1:


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



回答2:


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




回答3:


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"


来源:https://stackoverflow.com/questions/15258313/finding-with-string-find

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!