2013-11-26 120 views
7

我在Lua中遇到了一個問題,以檢查字符串值是否在另一個字符串中不存在。Lua - 獲取indexOf字符串

這就是我如何可能會做它在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.. 

回答

12

如已經提到的那樣,-是一個模式元字符,specifically

  • 單個字符類後跟「 - 」,這也匹配類中的字符的0或多次重複。與'*'不同,這些重複項目將始終匹配最短的序列;

你可能會感興趣的plain選項string.find。這將避免將來需要逃脫其他任何事情。

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

-是lua中的模式元字符。你需要逃避它。 string.find('no-cache', 'no%-cache')