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

lua, lua-patterns, pattern-matching

Solution

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

Problem

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?

Original source