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.

Beth Knight
  • 187
  • 2
  • 15

2 Answers2

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.

Aki
  • 2,818
  • 1
  • 15
  • 23
  • 1
    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. – Luatic Jul 29 '22 at 18:51
  • @LMD, Yes, around 5 times worse in case of the example. – Aki Jul 29 '22 at 21:50
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.

lhf
  • 70,581
  • 9
  • 108
  • 149
  • 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). – Aki Jul 30 '22 at 09:41