替换lua中包含特殊字符的字符串 [英] Replacing strings in lua containing special characters
本文介绍了替换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)
这篇关于替换lua中包含特殊字符的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文