Search code examples
lualua-patterns

Lua pattern doesn't work


I have trouble on my test script

names.txt contents
foo 1
test 0

data="names.txt"
name="test"
--
d=io.open(data,"r")
s=d:read("*a")
f=string.gsub(s,"%"..name,"%1 1")
print(f)
print"------"
print(f:gsub("(%w+)%s*(%d)","%1"):format("%s"))

output on lua

foo 1
test 1 0
------
foo
test 0

I would like to get the first number with string

from test 0 to test 1

I hope someone can help me


Solution

  • Is that what you are trying to do?

    data="names.txt"
    name="test"
    --
    d=io.open(data,"r")
    s=d:read("*a")
    f=string.gsub(s,"(" .. name .. ")%s+%d+","%1 1")
    print(f)
    

    Result:

    foo 1
    test 1
    

    If not, please be more precise. What output do you want?