Search code examples
stringlualua-patterns

Lua - Find "tags" in string?


I'm planning on using Lua patterns, unless there's a better way to do this.

I want to be able to parse a string, and look for "tags". For example, I'd like to find the '[color=???][/color]' part of a string, not care what comes after the equals, not care what's inbetween the tags and not care where the are in the string, as long as they are somewhere in the string, and that 'color=' has a hex value after it. Here is a sample string:

mystring = 'Hello, [color=#0026FF]world[/color]!'
--                 ^^^^^^^^^^^^^^^     ^^^^^^^^

Solution

  • Patterns in the manual

    First step, split the tokens:

    function split_tag(s, i)
      i = (i or 0) + 1
      local j = s:sub(i, i)
      if j == "" then
        return
      end
      j = s:find(j == "[" and "]" or ".%f[[\0]", i) or #s
      -- In Pre-5.2 Lua use %z instead of \0 in the pattern
      return j + 1, s:sub(i, j)
    end
    for k, v in split_tags, 'Hello, [color=#0026FF][bold]world[/bold][/color]!' do
      print(('%q\n'):format(v))
    end
    

    Thus, you get your input string

    'Hello, [color=#0026FF][bold]world[/bold][/color]!'
    

    split into

    "Hello, "
    "[color=#0026FF]"
    "[bold]"
    "world"
    "[/bold]"
    "[/color]"
    "!"
    

    Standard parentheses matching algorithm left as an exercise for the reader.