Reputation:
Lua patterns include %b()
and the like to capture strings enclosed by paired strings (in this case, parentheses). However, what if I want to capture everything except "%b()"
?
What I've tried:
str = "A time ago (hello)"
string.gsub(str, "[^%b()]", "a")
But the result is aaaaaaaaaaa(aaaaa)
, i.e., it replaces everything except paired parentheses. What I want to get is aaaaaaaaaaa(hello)
instead.
For more context, what I want is to make the following
myfunction("A nice (house) on an (island)")
--should ignore (house) and (island)
--should work like string.gsub(str, "%w+", "bla"), for instance
--by ignoring enclosed strings
bla bla (house) bla bla (island)
Upvotes: 1
Views: 298
Reputation: 72422
Try this code:
s="A nice (house) on an (island)"
print(s:gsub("(.-)(%b())",function (a,b) return a:gsub("%w+","bla")..b end))
This works, except that it does not handle the words after the last parentheses. The solution is to make sure that the input is uniform:
s="A nice (house) on an (island) in the Pacific" .. "()" -- here!
print(s:gsub("(.-)(%b())",function (a,b) return a:gsub("%w+","bla")..b end))
and then remove the trailing ()
in the output.
Upvotes: 0