0

How catch the values (r = 32, g = 36, b = 51) from this data above?

$color1: rgba(32, 36, 51, 1);

I try:

v = "$color1: rgba(32, 36, 51, 1);"
id, r, g, b = v.match(v, "%$color(%d+)%:%s+rgba%((%d+)%,%s+(%d+)%,%s+(%d+)%,%s+%d+%)%;") or 0, 0, 0, 0

But does not work.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Morogorn
  • 49
  • 1
  • 5

2 Answers2

0
v = "$color1: rgba(32, 36, 51, 1);"
string.gsub(v, "%((%d+),%s(%d+),%s(%d+)", function(r, g, b) print(r, g, b) end)

Output: 32 36 51

Gsub finds occurrences of a pattern in a string and will either replace text with text or in this case, run a function. I start my pattern with %( because I assume you're only going to run this function on a string that always looks like the one you've given, so there can be no false positives, so it will be pretty safe to just start at the first opening parenthesis. Each %d+ finds one or more digit, and it is wrapped in parentheses so the function can find it later. ,%s finds a comma and a space between the digits.

function(r, g, b) acts where r, g and b are the first, second and third set found in parenthesis.

Allister
  • 903
  • 1
  • 5
  • 15
0

Your id, r, g, b = v.match(v, "%$color(%d+)%:%s+rgba%((%d+)%,%s+(%d+)%,%s+(%d+)%,%s+%d+%)%;") or 0, 0, 0, 0 line is parsed by Lua as

id = v:match(pattern) or 0
r = 0
g = 0
b = 0

Since there is a match, the id variable is set to the capturing group 1 value, the rest is assigned with zeros.

You may fix this assignment using tables:

result = {string.match(v, "%$color(%d+):%s+rgba%((%d+),%s+(%d+),%s+(%d+),%s+%d+%);")}
id, r, g, b = result[1] or 0, result[2] or 0, result[3] or 0, result[4] or 0

See the Lua demo.

NOTE:; and , are not special Lua pattern characters, hence I removed % escapes in front of them in the pattern.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563