dimanche 29 janvier 2017

Getting string characters inside, and outside a set of brackets with string patterns in Lua?

I'm trying to create a string pattern that will match both non-space characters, and all characters inside a set of brackets. For example, a sequence such as this:

local str = [[
    This [pattern] should [return both] non-space 
    characters and [everything inside] brackets
]]

Would print out This, [pattern], should, [return both], non-space ... etc. I've been going at this for a while, and came up with a very close solution that I know the problem to, but cannot seem to solve. Here's my attempt:

local str = [[
    This [pattern] should [return both] non-space 
    characters and [everything inside] brackets
]]

for s in string.gmatch(str, "%S+%[?.-%]?") do
    print(s)
end

The issue is that spaces should be allowed inside the brackets, but not outside. This would print something like: This, [pattern], should, [return, both], non-space ... etc

Notice that [return and both] are two different captures, opposed to returning [return both]. I'm still sort of new to string patterns, so I feel like there's a few options I could be overlooking. Anyway, if anyone is experienced with this sort of thing, I sure would appreciate some insight.

Aucun commentaire:

Enregistrer un commentaire