本文介绍了Lua string.gsub()通过'%s'或'\ n'模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

英语不是我的母语,所以很难描述这个问题.
我想通过lua string.gsub()在str中获得"d = 40",但是有一些问题.

English isn't my mother tongue,so it's a little hard to describe the question.
I wanna to get 'd=40' in str by lua string.gsub(),but there's some problem.

本地pat1 = [= [%s [%s]] =]
本地pat2 = [= [\ n [%s]] =]
str:gsub(pat1,函数print("pat1 >>" .. s)结尾)--pat1 >> d = 40
str:gsub(pat2,函数print("pat2<<" .. s)结尾)-不匹配

local pat1 = [=[%s[%s]]=]
local pat2 = [=[\n[%s]]=]
str:gsub(pat1, function(s) print("pat1>>" .. s) end) --pat1>>d=40
str:gsub(pat2, function(s) print("pat2<<" .. s) end) --not match

本地re1,_ = str:gsub("\ n","$")
本地re2,_ = str:gsub(%s","$")
print(re1)--a = 10 $--b = 20 $ --c = 30 $ d = 40 $
print(re2)-$ a = 10 $-$-b = 20 $$ --c = 30 $ d = 40 $

local re1,_ = str:gsub("\n","$")
local re2,_ = str:gsub("%s","$")
print(re1) --a=10$- -b=20$ --c=30$d=40$
print(re2) --$a=10$-$-b=20$$ --c=30$d=40$

Lua 5.1参考手册说
%s:代表所有空格字符.
我认为它等于'\ n','和'\ t'.

As Lua 5.1 Reference Manual Say
%s: represents all space characters.
I Think it equal to '\n',' 'and'\t'.

问题:为什么pat2无法匹配?
但我认为pat2是正确的,有一个'\ n'befor'd = 40',
所以我认为它可以匹配,但不能正常运行,为什么?

Question : Why pat2 can't match?
But I think pat2 is right,there's a '\n'befor'd=40' ,
so I think It can match ,but it can't work,why?

推荐答案

当对字符串使用[[]]表示法时,这是一种特殊的字符串文字,其使用的字符串与您提供的字符串完全相同.没有字符转义.您可以将一些=字符放在方括号中,以使其更容易使用[字符串中的字符.

When you use [[]] notation for strings, that's a special string literal that takes the string exactly as you provide it. No character escaping is done. You can put some number of = characters in the brackets, to make it a bit easier to let you use [ characters in the string.

字符串文字"\n"是一个字符,表示换行符.这是因为使用了转义字符\.应用于'n'字符的转义字符表示换行符".

The string literal "\n" is one character, representing the newline. That's because of the use of the escape character \. The escape character applied to the 'n' character means "the newline character."

字符串文字[[\n]]就是它所说的:字符'\',后跟字符'n'.因为没有进行转义,所以\n不会被特殊对待.正是它的外观.

The string literal [[\n]] is exactly what it says: the character '\' followed by the character 'n'. Because no escaping is done, \n is not treated specially. It's exactly what it looks like.

因此,当您说local pat2 = [=[\n[%s]]=]时,您说的是第一个字符应为'\',后跟'n',后跟一个空格.这不是您想要的;您想要转义,所以您应该使用常规字符串文字:local pat2 = "\n[%s]".

Therefore, when you say local pat2 = [=[\n[%s]]=] You're saying "the first character should be '\' followed by 'n' followed by a space. That's not what you want; you want the escaping to work. So you should use a regular string literal: local pat2 = "\n[%s]".

这篇关于Lua string.gsub()通过'%s'或'\ n'模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 21:31