Lua 或查找并替换

Lua 或查找并替换

我的LaTeX-out.tex TeX 代码是(单行):

\begin{align*}\alpha + \beta = \gamma\end{align*} Some text here. \begin{align*}\sum^{k}_{i=1} \iota \end{align*} and so on the text. \begin{thebibliography}{000}\bibitem{cqgab7bbabib1}{Aasi J et al LIGO Scientific and VIRGO Collaborations 2014 Constraints on cosmic strings from the LIGO-Virgo gravitational-wave detectors.} \bibitem{cqgab7bbabib2}{Abbott B P et al LIGO and Virgo Collaborations 2016 Astrophysical implications of the binary black hole merger GW150914 L22} \bibitem{cqgab7bbabib3}{Abbott B P et al LIGO and Virgo Scientific Collaboration 2016 Search for transient gravitational waves in coincidence with short duration radio transients during 2007–2013}. \bibitem{cqgab7bbabib4}{Abbott B P et al The LIGO Scientific and Virgo Collaborations 2018 GWTC-1: a gravitational-wave transient catalog of compact binary.}

我的Lua Code是(我想在 \begin 之前输入(\n)并在 \bibitem 之前输入(\n):

local file = io.open("LaTeX-out.tex")
local fileedited = io.open("LaTeX-Updated.tex", "w")
local content = file:read "*a"
file:close()
contentmodified = string.gsub(content, [[\begin]], [[\n\begin]])
contentmodified = string.gsub(content, [[\end]], [[\n\end]])
contentmodified = string.gsub(content, [[\bibitem]], [[\n\bibitem]])
contentmodified = string.gsub(content, [[(\begin or \end)]], [[\n%1]])--it's not working **or**
fileedited:write(contentmodified)
fileedited:close()

但它只需要最终查找和替换(例如\bibitem)并忽略\开始\结尾。如何解决?

答案1

您不需要"这样[[,这\n意味着换行符,并且您需要将后续的替换应用于contentmodified先前更改的结果,而不是原始字符串。

local file = io.open("LaTeX-out.tex")
local fileedited = io.open("LaTeX-Updated.tex", "w")
local content = file:read "*a"
file:close()
contentmodified = string.gsub(content, [[\begin]], "\n\\begin")
contentmodified = string.gsub(contentmodified, [[\end]], "\n\\end")
contentmodified = string.gsub(contentmodified, [[\bibitem]], "\n\\bibitem")
fileedited:write(contentmodified)
fileedited:close()

生产


\begin{align*}\alpha + \beta = \gamma
\end{align*} Some text here. 
\begin{align*}\sum^{k}_{i=1} \iota 
\end{align*} and so on the text. 
\begin{thebibliography}{000}
\bibitem{cqgab7bbabib1}{Aasi J et al LIGO Scientific and VIRGO Collaborations 2014 Constraints on cosmic strings from the LIGO-Virgo gravitational-wave detectors.} 
\bibitem{cqgab7bbabib2}{Abbott B P et al LIGO and Virgo Collaborations 2016 Astrophysical implications of the binary black hole merger GW150914 L22} 
\bibitem{cqgab7bbabib3}{Abbott B P et al LIGO and Virgo Scientific Collaboration 2016 Search for transient gravitational waves in coincidence with short duration radio transients during 2007–2013}. 
\bibitem{cqgab7bbabib4}{Abbott B P et al The LIGO Scientific and Virgo Collaborations 2018 GWTC-1: a gravitational-wave transient catalog of compact binary.}

相关内容