寻找“.” 使用 string.find()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15258313/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 01:50:13  来源:igfitidea点击:

Finding '.' with string.find()

stringlualua-patterns

提问by user2141781

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:

我正在尝试进行简单的字符串操作:获取文件名,不带扩展名。只是,string.find()似乎点有问题:

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?

这是一个错误,还是我做错了什么?

回答by Joachim Isaksson

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

string.find(),默认情况下,不会在字符串中查找字符串,而是在字符串中查找模式。可以在链接中找到更完整的信息,但这里是相关部分;

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

编辑:或者,您可以传入一些额外的参数,find(pattern, init, plain)这允许您true作为最后一个参数传入并搜索纯字符串。那会让你的陈述;

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

回答by Egor Skriptunoff

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

string.find(s, '%.')string.find(s, '.', 1, true)

回答by greatwolf

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. 例如:

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