Lua string.gsub() by '%s' or '\n' pattern

不羁的心 提交于 2019-12-11 01:04:15

问题


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.

------code below---
local str = [==[
-- a=10
- -b=20
--c=30
d=40
]==]

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

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$

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

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?


回答1:


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.

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."

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.

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]".



来源:https://stackoverflow.com/questions/10156207/lua-string-gsub-by-s-or-n-pattern

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!