Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
5

Some help with specific string patters?

Asked by 8 years ago

This question is fairly short and to the point, basically I just need help with what string pattern I should be using here. I'm trying to make a function that will get all string in a text, except anything in cased in two bracket symbols ("[" , "]"). Here's my attempt:

local String = "This is a [ignored string] string that ignores [ignored again] certain blocks of text."

local function DecodeStr(Source)
    local new = ""
    for i in string.gmatch(Source, "[^%[.-%]]+") do
        new = new .. i
    end
    return new
end

print(DecodeStr(String))

Problem

The code above should ignore all blocks of text in between the brackets, and including the brackets, but instead just returns text without brackets (not ignoring the text inside them as well).

Is there any string pattern that could fix this so the result would look something like:

"This is a string that ignores certain blocks of text"

From the example above?

1 answer

Log in to vote
4
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
8 years ago

Lua has a nifty pattern %bxy which matches everything between (balanced) x and y. In your case,

function RemoveSquares(str)
    local new = str:gsub("%b[]", "")
    -- gsub is "global substitution": find and replace all.
    return new
end

print( RemoveSquares "alpha [beta] gamma [delta [epsilon]] theta" )
-- alpha  gamma  theta

Without %b, here are some options:

Building up the string:

    local x = ""
    for notbox in string.gmatch(str .. "[]", "([^[]*)%[[^%]]*%]") do
        x = x .. notbox
    end
    return x

Removing the parts you don't want:

    local x = str:gsub("%[[^%]]*%]", "")
    return x

Note that these last two do something different from the first one on some inputs:

The first one will turn x[[]]y into xy while the second two will make x]y. The difference is whether or not you want to "match" the brackets, or just use the first / first.


Also keep in mind, that in your example, there would be two spaces wherever you removed the [] since the space on the left and right would now be touching.

0
Thank you! CodingEvolution 490 — 8y
Ad

Answer this question