开发者

How to string.find the square bracket character in lua?

开发者 https://www.devze.com 2023-03-07 04:10 出处:网络
So I\'m trying to find square brackets inside a string: s = \"testing [something] something else\" x,y = string.find(s,\"[\")

So I'm trying to find square brackets inside a string:

s = "testing [something] something else"
x,y = string.find(s,"[")

which gives me an error: malformed pattern (missing ']').

I also tried:

x,y = string.find(s,"\[")

giving me the 开发者_运维问答same error.

And this:

x,y = string.find(s,"\\[")

in this case x and y are nil.

Any thoughts on how to do this properly? Thanks in advance.


John's answer will work -- turning off pattern matching.

What you're trying to do -- escape the [ -- is done with the % character in Lua:

 x,y = string.find(s,'%[')

Also strings in Lua all have the string module as their metatable, so you could just say:

 x,y = s:find('%[')

or even:

 x,y = s:find'%['


Use the fourth argument to string.find, which turns off pattern-matching.

x, y = string.find(s, "[", nil, true)
0

精彩评论

暂无评论...
验证码 换一张
取 消