Lua regex to match pattern in makefile

104 views Asked by At

I'm writing a script to automate the mantainment of my makefile. I need a Lua pattern that matches the following lines:

# objects {
objects = build/somefile1.o \
          build/somefile2.o \
          ...
          build/somefileN.o \

# } objects

I tried with %# objects %{[a-z%.%s%/%\\]+%# %} objects but it doesn't seem to work.

1

There are 1 answers

0
Wiktor Stribiżew On BEST ANSWER

I suggest using:

"\n(# objects %b{} objects)"

To make it work for cases when the match is at the start of the string, you need to prepend the string input with a newline. Here, a newline is matched first, then# objects, then a space, then %b{} matches balanced nested curly braces (if any) and then objects is matched.

When running the extraction, the captured part (within (...)) will be returned with string.gmatch.

See the Lua online demo

s = [[ YOUR_TEXT_HERE ]]
for m in string.gmatch("\n" .. s, "\n(# objects %b{} objects)") do
   print(m)
 end