Help with re:gmatch

Posted by Zim on Mon 26 Jan 2015 01:16 AM — 5 posts, 17,628 views.

#0
I'd like to take a block of text and create a table containing re matches. But I'm unsure of the correct way to do that. Here's a silly example to demonstrate what I'm trying to do.

text = "I like to eat apples for lunch. I like to eat pears for dinner. I don't like pizza. I like to eat veggies for fun!"

re = rex.new("I like to eat (.*?) for")

I'd like to end up with a table like:

1 apples
2 pears
3 veggies

How would I use re:gmatch to accomplish this?
Australia Forum Administrator #1
It's easy with Lua regular expressions:


food = string.match ("I like to eat apples, pears, veggies for dinner",  
                     "^I like to eat (.*) for")

t = { }

if food then
  print (food)
  for word in string.gmatch (food, "%a+") do
    table.insert (t, word)
  end -- for
else
  print ("No match")
end -- if

require "tprint"
tprint (t)


Output:


apples, pears, veggies
1="apples"
2="pears"
3="veggies"
Amended on Mon 26 Jan 2015 02:31 AM by Nick Gammon
#2
I appreciate the reply, but I need to know how to implement the new.rex because my actually code will require expressions that can't be done with basic lua matching.
#3

text = "I like to eat apples for lunch. I like to eat pears for dinner. I don't like pizza. I like to eat veggies for fun!"

re_food = rex.new("I like to eat (.*?) for")

my_matches = {}
re_food:gmatch(text, function (m, t) 
	for k, v in pairs(t) do
		table.insert(my_matches, v)
	end
end)

require "tprint"
tprint(my_matches)

I found that this works! But I still suspect there might be simpler syntax.
Amended on Mon 26 Jan 2015 03:16 AM by Zim
Australia Forum Administrator #4
Looks pretty simple to me.