替换lua中包含特殊字符的字符串
问题描述:
我要替换lua中的字符串.这是字符串.
I want to replace string in lua. Here is the string.
strng='\begin{matrix} 1 & 2 & 3 \\ 4 & 5 & 6 \\ 7 & 8 & 10 \end{matrix}'
我要替换
\begin{matrix} by {{
& by ,
\\ by },{
\end{matrix} by }}
我也想删除所有空格.因此输出将为
I also want to remove all spaces. So the output will be
{{1,2,3},{4,5,6},{7,8,10}}
我编写了以下函数来实现这一目的.
I have written the following function to do this.
function tempsubst(m1)
m1 = matrixprint(m1)
if type(m1) ~="string" then return m1 end
m1 = string.gsub(m1,"\begin%{matrix%}","{{" )
m1 = string.gsub(m1,"\\","},{" )
m1 = string.gsub(m1,"%&","," )
m1 = string.gsub(m1,"end%{matrix%}","}}" )
m1= string.gsub(m1 , "%s+", "")
return m1
end
这有时会起作用,但有时会不起作用.函数中肯定有错误.我是lua的新手.代码可以更正吗?任何帮助将不胜感激.谢谢.
This sometimes work but sometimes it does not work. There must be mistakes in the function. I am newbie to lua. Could the code be corrected? Any help will be appreciated. Thanks.
答
当与转义符和反斜杠混淆时,最好使用不解释它们的长字符串:
When confused with escapes and backslashes, it's better to use long strings, which don't interpret those:
m1=[[\begin{matrix} 1 & 2 & 3 \\ 4 & 5 & 6 \\ 7 & 8 & 10 \end{matrix}]]
print(m1)
m1 = string.gsub(m1,[[\begin{matrix}]],"{{" )
m1 = string.gsub(m1,[[\\]],"},{" )
m1 = string.gsub(m1,[[&]],"," )
m1 = string.gsub(m1,[[\end{matrix}]],"}}" )
m1= string.gsub(m1 , [[%s+]], "")
print(m1)