View Full Version : How do I separate out text between two search terms in a string?

March 21st, 2015, 05:00 PM
I need to get out a part of a response from the JRMC web server interface. It comes in this form (only the necessary excerpt):

<Response Status="OK"><Item Name="NumberZones">12</Item><Item Name="CurrentZoneID">10007</Item><Item Name="CurrentZoneIndex">8</Item><Item Name="ZoneName0">Tor</Item><Item Name="ZoneID0">0</Item><Item Name="ZoneGUID0">{3ECD3C04-2C29-4F23-8F99-0E134C0BE5D2}</Item><Item Name="ZoneName1">Stua</Item><Item Name="ZoneID1">10000</Item>

What I need to do in this response is to search for ZoneID1 and then make the part 10000 into a variable. I can find the necessary bit easily enough (the variable sent into this is the number of the zone I need the ID from):

local Sone = 1
local soneliste = socket.http.request("")
local i = string.find(soneliste, 'ZoneID'..Sone)
local sonenummer = string.sub(soneliste, i+9, i+13)

This gives me this output:


But if I try the first zone, zone 0, I get:


Since that's only one digit I get 4 extra symbols. I could of course to an if then to check if the zone number is 0, but I have another place I would like to use the same stuff, and that's more varying what will be in the result. So is there a way to find first the search term and then the first instance of a second search term? So I can search for SoneID1 and then search for the first instance of < after that, and then use the part that's between them?

March 21st, 2015, 05:58 PM
Not the most elegant solution, but it works.

local _, _, sonenummer0 = string.find(soneliste, 'ZoneID0">(%d+)<')
local _, _, sonenummer1 = string.find(soneliste, 'ZoneID1">(%d+)<')
print (sonenummer0,sonenummer1)

March 22nd, 2015, 05:31 AM
Thanks, Rick! It's more elegant than you think. Because I can do it with any zone like this:

local Sone = 11
local soneliste = socket.http.request("")
local _, _, sonenummer = string.find(soneliste, 'ZoneID'..Sone..'">(%d+)<')
print (sonenummer)

So this gives the sonenummer (or actual ID) of 100023. And so on :)