Lua - 获取字符串的索引位置

9

我需要在Lua中解决一个问题,即判断一个字符串值是否不出现在另一个字符串中。

这是我在JavaScript中的做法:

'my string'.indexOf('no-cache') === -1 // true

但在Lua中,我尝试使用 string 模块,但得到了意外的响应:

string.find('my string', 'no-cache') -- nil, that's fine but..
string.find('no-cache', 'no-cache') -- nil.. that's weird
string.find('no-cache', 'no') -- 1, 2 here it's right.. strange..
2个回答

15

正如已经提到的,- 是一个模式元字符,具体地说

  • 单个字符类后跟“-”,它还匹配字符类中0个或多个重复。与“*”不同,这些重复项总是匹配最短可能的序列;

您可能会对string.findplain选项感兴趣。这将避免将来需要转义其他任何内容。

string.find('no-cache', 'no-cache', 1, true)

8

- 是 lua 中的一种模式元字符,需要进行转义处理。string.find('no-cache', 'no%-cache')


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接