2

From strings that are similar to this string:

|cff00ccffkey:|r value

I need to remove |cff00ccff and |r to get:

key: value

The problem is that |cff00ccff is a color code. I know it always starts with |c but the next 8 characters could be anything. So I need a gsub pattern to get the next 8 characters (alpha-numeric only) after |c.

How can I do this in Lua? I have tried:

local newString = string.gsub("|cff00ccffkey:|r value", "|c%w*", "")
newString = string.gsub(newString, "|r", "")

but that will remove everything up to the first white-space and I don't know how to specify the max characters to select to avoid this.

Thank you.

Mayron
  • 2,146
  • 4
  • 25
  • 51

1 Answers1

2

Lua patterns do not support range/interval/limiting quantifiers.

You may repeat %w alphanumeric pattern eight times:

local newString = string.gsub("|cff00ccffkey:|r value", "|c%w%w%w%w%w%w%w%w", "")
newString = string.gsub(newString, "|r", "")
print(newString)
-- => key: value

See the Lua demo online.

You may also make it a bit more dynamic if you build the pattern like ('%w'):.rep(8):

local newString = string.gsub("|cff00ccffkey:|r value", "|c" ..('%w'):rep(8), "")

See another Lua demo.

If your strings always follow this pattern - |c<8alpnum_chars><text>|r<value> - you may also use a pattern like

local newString = string.gsub("|cff00ccffkey:|r value", "^|c" ..('%w'):rep(8) .. "(.-)|r(.*)", "%1%2")

See this Lua demo

Here, the pattern matches:

  • ^ - start of string
  • |c - a literal |c
  • " ..('%w'):rep(8) .. " - 8 alphanumeric chars
  • (.-) - Group 1: any 0+ chars, as few as possible
  • |r - a |r substring
  • (.*) - Group 2: the rest of the string.

The %1 and %2 refer to the values captured into corresponding groups.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • And there is definitely no easier/nicer way to specify the number of %w needed? – Mayron Nov 18 '18 at 16:27
  • @Mayron If you mean a [limiting quantifier](https://www.regular-expressions.info/repeat.html#limit), no, it is not possible. – Wiktor Stribiżew Nov 18 '18 at 16:32
  • Thank you. I didn't know if there was a nice way of possibly combining those 2 gsub calls by using a regex pattern to say something like "only substitute things that are inside these brackets" (like how c# can assign matches of text to groups): `"(|c%w%w%w%w%w%w%w%w").*(|r)*."`, but I think Lua is very simple (if it cannot have range support then I doubt it could do that). – Mayron Nov 18 '18 at 16:33
  • @Mayron Will your input strings always contain only a single key-value pair? – Wiktor Stribiżew Nov 18 '18 at 16:36
  • It's hard to say if it "always" will, but for now yes. Thank you for expanding on your answer. I was busy working and only just checked! – Mayron Nov 18 '18 at 17:45