Lua return end value in a string

Viewed 102

If I have this string: "wwww:xxxx:yyyy:zzzzzz:0"

How can I return only the "zzzzzz:0" value? Knowing that zzzzz will not always be the same length.

2 Answers

Use Patterns for this:

 string.match("wwww:xxxx:yyyy:zzzzzz:0", "[^:]+:[^:]+$")  --> 'zzzzzz:0'

This is naïve and focuses entirely on expressing this particular intent. [^:]+ matches a sequence of one or more characters that are not :, : after that matches itself, and $ matches the end of the string.

Based on the format of your string, you might want to look into splitting the string using : as a separator. This can be accomplished with e.g., string.gmatch and the [^:]+ pattern from above. See Split string in Lua? for a detailed explanation of this problem.

In a complex situation where the components are expected to e.g., support quoting or escape sequences, and if you are highly concerned with time or memory optimisation you should look to use a csv-like parser.

Try also this somewhat simpler pattern:

string.match("wwww:xxxx:yyyy:zzzzzz:0", ".+:(.+:.+)$")

It looks for the last item of the form foo:bar.

Related