dimanche 11 août 2019

How to Ignore Nested Brackets in a String in Lua?

I have a set of special characters that can be thought of as brackets. When a user encloses some text between these brackets, I simply want the program to replace whatever brackets were used, with <, >. So, if *, * are the brackets and the string is "Hello *world*", the program should return "Hello <world>".

The problem is I want to avoid nested occurrences of these bracket pairs, and I only want the program to focus on the outermost pair. In other words, once an opening bracket is made, treat all of the characters as normal characters until the opening bracket is closed.

For example, if my brackets are *, * and #, # and my string is "Hello *wo#rl#d*", the program should return: "Hello <wo#rl#d>" instead of: "Hello <wo<rl>d>"

I've tried using string.gsub to find all patterns of text between the defined special characters, but of course, it won't ignore nested occurrences of them.

local specialChars = {"*", "#", "-"}
local text = "Hello, world. *Won#der#ful* day, -don't- you #th*in*k?#"

for i = 1, #specialChars do
    local bracket = specialChars[i]
    local escBracket = "%" .. bracket

    text = string.gsub(text, escBracket .. "(.-)" .. escBracket, function(content)
        return "<" .. content .. ">"
    end)
end

print(text)

The code above should display:

"Hello, world. <Won#der#ful> day, <don't> you <th*in*k?>"

but instead displays:

"Hello, world. <Won<der>ful> day, <don't> you <th<in>k?>"

Any help would be greatly appreciated.

Aucun commentaire:

Enregistrer un commentaire