Reputation: 458
In a string like {any {possible} characters}{anything}
I want to delete the last {...}
occurrence, which itself can not include another {...}
combination. No problem with searching the last {
and then using string.sub
.
However is there a short command with pattern matching which strips the last one like:
str = "{any {possible} characters}{anything}"
print(str:gmatch(...))
should write {any {possible} characters}
Upvotes: 3
Views: 511
Reputation: 626932
Here are two possible solutions.
No nested braces at the end:
string.gsub('{any {possible} characters}{anything}', '{[^{}]*}$', '')
Here, {[^{}]*}$
matches a {
, then any 0+ chars other than {
and }
, and then a }
char that must be at the end of the string ($
).
If there are nested braces at the end use the following:
string.gsub('{anything}{any {possible} characters}', '%b{}$', '')
Here, %b{}$
matches a {...}
substring with any amount of nested braces inside and then asserts the position at the end of the string with $
.
See this Lua demo
Note that you may add %s*
to match any 0+ whitespaces (it is useful if there is trailing whitespace, e.g.) - '%b{}%s*$'
.
Upvotes: 4