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}
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*$'.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With