寻找“."使用 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;
'.'表示通配符,可以表示任意字符.
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, %.
或者,您可以传入一些额外的参数,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屋!