2

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 2

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Pretty sure "naive" in this case means worst-case exponential runtime, so I'd definitely recommend going the gmatch route you have outlined if this ever sees user input.
@LMD, Yes, around 5 times worse in case of the example.
1

Try also this somewhat simpler pattern:

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

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

1 Comment

Note that in this case the string must have at least three component (which is a fair assumption in situations like this). Otherwise, one can e.g., prepend delimiting character to the string (in that case you only need to ensure two components, and that's even a better assumption since we're looking for the last two).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.