Help with string.find encapsulation

A server I am calling to is returning data in a custom format that looks something like this:

“DATA[foo],DATA[bar]”

I am trying to write a helper function that will strip the data out from the string and only return me the “foo” and the “bar”.  In my function I am trying to use the string find command to locate the beginning of the data. So I would like to do something like this to get a starting point:

param_start = string.find(returned_string, “DATA[”)

but when I run this I am getting an error that says:  “malformed pattern (missing ‘]’)”

It looks like I need to encapsulate the [ after the word DATA but I cannot figure out how to do it.  Can anyone help me out?

To try it out I pasted the following in the lua demo page (http://www.lua.org/cgi-bin/demo)

foo = “this is DATA[33] test”
bar = string.find(foo, “DATA[”)
print(“data starts at”…bar)

if, in line 2, I change “DATA[” to just “DATA” it works fine but I would get the starting point of [ instead of the 33.

Thank you in advance!!

The ‘[’ is a “magic” character in lua so you need to escape it using  ‘%’. So

foo = “this is DATA[33] test”

bar = string.find(foo, “DATA%[”)

print("data starts at "…bar)

shouldn’t give you any errors.  But ‘bar’ will be the position where the pattern _starts _so you will still need to add the length of the pattern to find the position where your data actually starts, in this case bar + 5.

EDIT:  this would get you the start position of your actual data:

foo = “this is DATA[33] test”

barStart, barEnd = string.find(foo, “DATA%[”)

print("data starts at "…(barEnd + 1))

Here’s reference on lua patterns, magic characters, and escaping them:

http://www.lua.org/pil/20.2.html

Brilliant!  Thank you very much for the answer as well as the reference!

The ‘[’ is a “magic” character in lua so you need to escape it using  ‘%’. So

foo = “this is DATA[33] test”

bar = string.find(foo, “DATA%[”)

print("data starts at "…bar)

shouldn’t give you any errors.  But ‘bar’ will be the position where the pattern _starts _so you will still need to add the length of the pattern to find the position where your data actually starts, in this case bar + 5.

EDIT:  this would get you the start position of your actual data:

foo = “this is DATA[33] test”

barStart, barEnd = string.find(foo, “DATA%[”)

print("data starts at "…(barEnd + 1))

Here’s reference on lua patterns, magic characters, and escaping them:

http://www.lua.org/pil/20.2.html

Brilliant!  Thank you very much for the answer as well as the reference!