qhouz
qhouz

Reputation: 35

Lua matching wrong pattern

I need to match string and return (\aHEX) and (text).

And use it like

for k, v in string.gmatch("Default \aFFFFFFFFWhite text \aFF0000FFJust red text", "<pattern>") do
    -- k = "" / "\aFFFFFFFF" / "\aFF0000FF"
    -- v = "Default" / "White text " / "Just red text"
end

tried this

local text = "Default \aFF00FFFFRed text\a00FF00FFGreen";

for k, v in text:gmatch("(\a%x%x%x%x%x%x%x%x)(%w+)") do
    print(string.format("%s: %s", k, v));
    -- \aFF00FFFF: Red
    -- \a00FF00FF: Green
end

Missing "Default" and " text"

Upvotes: 2

Views: 55

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626728

The problem is that you cannot make a sequence of patterns optional with Lua patterns.

You can use

local text = "Default \aFF00FFFFRed text\a00FF00FFGreen";
 
for word in text:gmatch("\a?[^\a]+") do
  k, v = word:match("^(\a%x%x%x%x%x%x%x%x)(%w+)$")
  if k then
     print(string.format("%s: %s", k, v));
  else
     print(word)
  end
end

Output:

Default 
FF00FFFFRed text
00FF00FF: Green

Details:

  • \a?[^\a]+ matches all occurrences of sequences that start with an optional \a, and then contain one or more chars other than \a
  • then ^(\a%x%x%x%x%x%x%x%x)(%w+)$ is applied to each found substring, and if there is a match, the key:value pair is produced, else the whole match is the required value.

Upvotes: 2

Related Questions