查找“."用string.find() [英] Finding '.' with string.find()
问题描述
我试图做一个简单的字符串操作:获取文件名,不带扩展名.只是,string.find()
似乎存在点问题:
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
并且仅带点:
s = 'crate.png'
i, j = string.find(s, 'p')
print(i, j) --> 7 7
是一个错误,还是我做错了什么?
Is that a bug, or am I doing something wrong?
推荐答案
string.find()
默认情况下不会在字符串中找到字符串,而是找到
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, %.
或者,您可以传入一些额外的参数,find(pattern, init, plain)
,它允许您传入true
作为最后一个参数,并搜索纯字符串.那将使您发表声明;
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
这篇关于查找“."用string.find()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!