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

2

14

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.

Normand answered 20/5, 2011 at 20:47 Comment(0)
L
22

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'%['
Lezlielg answered 20/5, 2011 at 20:55 Comment(0)
H
8

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

x, y = string.find(s, "[", nil, true)
Hum answered 20/5, 2011 at 20:51 Comment(3)
That works fine, thank you. But what I'm trying to do now it to find this pattern: "[..:..]" which means: a bracket, two '.' meaning any character, the ':', again 2 '.', and another bracket. Should I split the problem in 2 or more string.find? Thanks.Normand
Oh Mud anwsered that: just use the '%[' so now i can use '.' as a wildcard character. thanks againNormand
Right—in that case use Mud's answer. You can escape a character such as [ with the % symbol; so you could use a pattern of "%[..:..%]".Hum

© 2022 - 2024 — McMap. All rights reserved.