Lua - get indexOf string

巧了我就是萌 提交于 2019-12-21 12:37:55

问题


I am stuck with a problem in Lua to check whether the string value is not presented in another string.

That's how I likely will do it in Javascript:

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

but in Lua I'm trying to use string module which gives me unexpected response:

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..

回答1:


As has already been mentioned, - is a pattern metacharacter, specifically:

  • a single character class followed by '-', which also matches 0 or more repetitions of characters in the class. Unlike '*', these repetition items will always match the shortest possible sequence;

You might be interested in the plain option for string.find. This will avoid the need for escaping anything else in the future.

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



回答2:


- is a pattern metacharacter in lua. You need to escape it. string.find('no-cache', 'no%-cache')



来源:https://stackoverflow.com/questions/20222916/lua-get-indexof-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!