# Lualatex code to select enclosed text from another file

I am trying to write a function that would select a text delimited by some symbols (*) from another file and print it. The following gives an error. What is the right way to pass 'text' to string.gsub?

\documentclass{scrartcl}
\usepackage{luatextra}
\usepackage{filecontents}

\begin{filecontents}{testdata.dat}

a *string enclosed in* stars

\end{filecontents}

\begin{luacode*}
file = io.open("testdata.dat", "r")
file:close()
for x in string.gsub(text,"*(.*)*","") do
tex.print(x)
end
end
\end{luacode*}

\begin{document}
\end{document}

• Are you sure you want to use *(.*)*? This does not select the literal * which you seemingly want to use as delimiter… Jan 22, 2019 at 20:22

You need to use gmatch instead of gsub. And probably non greedy regexp (.-) if there are more then one match:

\documentclass{scrartcl}
\usepackage{luatextra}
\usepackage{filecontents}

\begin{filecontents}{testdata.dat}

a *string enclosed in* stars *two*

\end{filecontents}

\begin{luacode*}
file = io.open("testdata.dat", "r")
file:close()
for x in string.gmatch(text,"*(.-)*") do
tex.print(x)
end
end
\end{luacode*}

\begin{document}

• tex.print(x .. "\\par") Jan 23, 2019 at 6:37