Search code examples
stringlualua-patterns

How to get one, two, three or none occurrences with string.match in Lua?


Well given a string like this: local filename = "Help1_Index of Contents_Comments_EN.png", I can get the three occurrences (🤔 are they even called occurrences? Anyway...) by means of this: local first, second, third = filename:match("_(.-)_(.-)_(.-)"), so far so good...

BUT, turns out it only works as long as there are indeed three occurrences in the string, so in a string like this: "Help1_Index of Contents_Comments.png" no one is returned even there are two of them... I've been told using "?" should make it work no matter the number of the occurrences present in the string, e.g. this ways: local first, second, third = filename:match("_(.-)?(.-)?(.-)?") or local first, second, third = filename:match("_(.-)?_(.-)?_(.-)?"), but no matter how I try to implement such advice, the function simply stops returning anything.

Well, I wanted to use string.match instead of string.gmatch for simplify, but it's clear I'm already beating around the bush on this... So at this point any input would be welcomed. Thanks.


Solution

  • Try this pattern:

    _([^_]*)_?([^_]*)_?([^_]*)$