Reputation: 101
I am using lua to parse through a large string sequence I am given from an api request. The received string sequence looks something like this:
<stats>+200 Stock Price<br>+100% Stock Price Increase <br><stock>+100% Stock Size</stock><br>+10% Company Revenue
So I would need, for example, to get the number of "Stock Price Increase" so I can do calculations on it later in my coding. The string always comes in this format, but the location of where each variable is can be random. For example, "Stock Price" can be sent at the beginning, middle or end of the string, and there is no pattern for knowing its location.
Any help provided would be appreciated!
Upvotes: 2
Views: 44
Reputation: 72432
Here is a solution that does not need to know the names of the fields:
S=[[
<stats>+200 Stock Price<br>+100% Stock Price Increase <br><stock>+100% Stock Size</stock><br>+10% Company Revenue
]]
S=S.."<"
for v,k in S:gmatch(">([-+].-)%s+(.-)%s*<") do
print(k,v)
end
Instead of printing, you could store the data in a table.
Upvotes: 1
Reputation: 627607
It seems you can use several patterns to get the values you need using Lua patterns.
Note that to match any digit, there is a %d
shorthand class, and to match any whitespace, %s
. Note that a %
symbol is used to escape these chars, and to match a literal %
symbol, you will need to double it %%
.
See the Lua demo:
s = [[<stats>+200 Stock Price<br>+150% Stock Price Increase <br><stock>+110% Stock Size</stock><br>+10% Company Revenue]]
print(string.match(s, [[(%d+%%)%s+Stock Price Increase]]) .. " - Stock Price Increase")
print(string.match(s, [[(%d+%%)%s+Stock Size]]) .. " - Stock Size")
print(string.match(s, [[(%d+%%)%s+Company Revenue]]) .. " - Company Revenue")
print(string.match(s, [[(%d+)%s+Stock Price]]) .. " - Stock Price")
Output:
150% - Stock Price Increase
110% - Stock Size
10% - Company Revenue
200 - Stock Price
Upvotes: 2