Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua pattern to stop when end of line

I need to get help for a pattern in Lua stopping to read after a line break. My code:

function getusers(file)
local list, close = {}
    local user, value = string.match(file,"(UserName=)(.*)")
    print(value)
    f:close()
end

f = assert(io.open('file2.ini', "r"))
local t = f:read("*all")
getusers(t)


--file2.ini--

user=a
UserName=Tom
Password=xyz
UserName=Jane

Output of script using file2.ini:

Tom

Password=xyz

UserName=Jane

How to get the pattern to stop after it reaches the end of line?

like image 425
Pekinese Avatar asked Oct 15 '25 16:10

Pekinese


1 Answers

You can use the pattern

"(UserName=)(.-)\n"

Note that besides the extra \n, the lazy modifier - is used instead of *.


As @lhf points out, make sure the file ends with a new line. I think you can append a \n to the string manually before matching.

like image 158
Yu Hao Avatar answered Oct 18 '25 06:10

Yu Hao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!