Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua: delete last {..}

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}

like image 693
Red-Cloud Avatar asked Dec 21 '25 03:12

Red-Cloud


1 Answers

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*$'.

like image 176
Wiktor Stribiżew Avatar answered Dec 23 '25 02:12

Wiktor Stribiżew