String Pattern confusion

You can write your topic however you want, but you need to answer these questions:

  1. What do you want to achieve? Keep it simple and clear!
    Hi, I want to know what the modifier %n does for and be able to use it correctly with string.match.
  2. What is the issue? Include screenshots / videos if possible!
    I cant seem to grasp how to use it from the dev-wiki.

The wiki states its definition as:
For n between 1 and 9 , matches a substring equal to the n -th captured string.
Then doesn’t give any practical examples.

  1. What solutions have you tried so far? Did you look for solutions on the Developer Hub?
    I’ve attempted to search around the forums to no avail. The only thing remotely even resembling it was talking about newline, or \n.
1 Like

In Lua % is used as the escape character, as its namesake suggests it “escapes” the intended purpose of a character, in this case the letter “n”, and gives it a special meaning, the escape sequence %n is used in string patterns to match a newline in the subject string (string being searched).

Read about that on the official website of Lua

I’m curious about this too, could someone tag me if they give an answer?

I’ve tried a few code samples from a few websites upon doing some research on substrings but I genuinely have no idea how or why they work.

local s = 'aaaaa' 
print(s:find('()aa()'))
--> 1 2 1 3???

I’ve also tried to do stuff like

local s = 'aaaaa'
print(s:find('%n()aa()'))
--> nil

I haven’t seen a single code sample using %n so it can’t be used that much, can it?
I think %n represents an integer value but I’ve never payed any regard to it, nor can I figure out why it even exists

local s = '%n' print(s:format(1)) --> errors
local s = '1' 
print(s:find('%n')) --> nil

local s = '1' 
print(s:find('%n()1()')) --> nil

local s = 'aaa' 
print(s:find('%n()a()')) --> nil

I also tried thinking n was a placeholder for a number, however doing anything like '%1()a()' also errors

string:find just returns where the matched characters start and end in the inputted string

The "%n" you are referencing are capture groups: %0, %1, %2, …

local a = "123 epic 123"
local b = a:gsub("%d", "_%1_")

print(b)

_1__2__3_ epic _1__2__3_

example of more capture groups in the same substitution:

local a = "123 epic 123"
local b = a:gsub("(%d)(%d)", "_%1_<%2>")

print(b)

_1_<2>3 epic _1_<2>3

This can be cleverly used to format numbers.

local n = 1234121
local f = tostring(n):reverse():gsub("(%d%d%d)", "%1,"):reverse()
print(f)

1,234,121

1 Like