5

I try to find a string in a HTML-Body, the string looks like var version="1,1,0,0"; and i only want to extract the content between the double quotes. I have tried it with

local version = string.match(response.body, ".version.") return version

loxi2017
  • 51
  • 1
  • 6

2 Answers2

3

You may use a var%s+version="([^"]+) pattern with string.match that will only output the captured text (i.e. the one matched with ([^"]+)) (see this Lua patterns tutorial):

s = [[var version="1,1,0,0";]]
res = string.match(s, [[var%s+version="([^"]+)]])
print(res)

See the Lua demo.

Details:

  • var - a literal var text
  • %s+ - 1+ whitespaces
  • version=" - literal version=" text
  • ([^"]+) - a capturing group matching 1+ chars other than ".

If you want to specify that there can only be digits and commas inside version="...", use var%s+version="([%d,]+) pattern (see demo) where [%d,]+ matches 1+ digits or commas.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
1
--> parsing first single quoted string only.
str1 = [[var version='1,1,0,0';]]
res1 = string.match(str1, "%b''")
res1 = string.gsub(res1, "'", '')
print(res1)

--> parsing first double quoted string only.
str2 = [[var version="1,1,0,0";]]
res2 = string.match(str2, '%b""')
res2 = string.gsub(res2, '"', "")
print(res2)


--> parsing all single quoted strings.
line1 = "major_ver='1', minor_ver='1.1'"
for chunk in string.gmatch(line1, "'(.-)'") do print(chunk) end

--> parsing all double quoted strings.
line2 = 'major_ver="2", minor_ver="2.2"'
for chunk in string.gmatch(line2, '"(.-)"') do print(chunk) end

line3 = [[major_ver="3", minor_ver="3.3"]]
for chunk in string.gmatch(line3, [["(.-)"]]) do print(chunk) end

Click on Lua demo for live result.