user2150130
user2150130

Reputation: 13

matching none or more Lua pattern

I am wondering if it was possible to make a pattern that could work like this:

With [icon=star w=32 h=32 spin=90], it would return a table with:

icon: star  
w: 32  
h: 32  
spin: 90

I've tried doing [icon=(.-) ((.-)=(.-))] but it breaks.

Upvotes: 1

Views: 168

Answers (4)

Paul Kulchenko
Paul Kulchenko

Reputation: 26744

for k, v in ("[icon=star w=32 h=32 spin=90]"):gmatch("(%w+)=(%w+)")
  do print(k..":",v) end

icon:   star
w:  32
h:  32
spin:   90

Upvotes: 0

hjpotter92
hjpotter92

Reputation: 80639

Lua doesn't have regex in the literal sense. It uses patterns.

So, for your case, I'd much rather use gsub(or gmatch):

local str = "[icon=star w=32 h=32 spin=90]"
local tR = {}
str:gsub( "(%w+)%=(%w+)", function( x, y ) tR[x] = y end )

And your tR will have the exact result you wanted.


More tutorials on gmatch and gsub are:

Upvotes: 3

Bohemian
Bohemian

Reputation: 425033

Try this:

(\w+)=(\w+)

Each match will have two groups:

  • Group 1 will be the "name"
  • Group 2 will be the "value"

Upvotes: 0

Daedalus
Daedalus

Reputation: 1667

Using the following expression: (\w+(?=\=))=((?<=\=)\w+) group 1 of each match would be the left hand side and group 2 of each match would be the right hand side.

Example: http://regexr.com?3478b

Upvotes: 1

Related Questions