How to match a string with pattern "["?

When I write string.match(str, "["), I get Invalid match pattern: expected ] at the end of the string to close a set. I want to find if [ exists in a string, but I don’t know why that error occurs.

Add a backslash:

string.match(str, "\[")

[” is a special character. Using a backslash lets the interpreter know you’re searching for the “[” literal instead of using it for special functionality.

[Edit] Corretion: use % instead of backslash. Refer to this reply:

1 Like

Actually, for this you’d use % since you’re looking for a string pattern (and \[ isn’t an escape character)

string.match(str, "%[")
1 Like

Good catch! I will edit my post accordingly. Thanks!

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.