Search code examples
lualua-patterns

LUA Pattern to retrieve a specific part of text from a string


So I have a string in Lua that is exactly like the following:

[[
  en[What is your job]
  pt[Qual é o seu trabalho?]
]]

As you might expect, I want to sometimes retrieve anything inside "en[]" and in other times "pt[]" and put the text inside a new variable.

Any ideas?


Solution

  • Edit: Improved speed by removing some concatenation.

    This should work:

        String = [[
            en[What is your job]
            pt[Qual é o seu trabalho?]
        ]]
    
        function RetrieveElementFromString( String, Element, ContainerOpen, ContainerClose ) -- String is the "[[]]" part.
            return String:match( Element .. ContainerOpen .. '(.-)' .. ContainerClose )
        end
    
        print( RetrieveElementFromString( String, 'en', '%[', '%]' ) ) -- > What is your job