12

I am new to Lua, and hardly understand pattern matching. I am trying to figure out how to match everything in a string after a colon, and put that portion of the string into a variable. I haven't had much luck by looking around online, or maybe I am just not seeing it. So how would I do this?

For example, say I have a variable called my_string that is equal to "hello:hi_there" or something like that. How can I extract "hi_there" to a another variable without changing my_string?

It looks like I would need to use string.match(), but what pattern would be used to achieve my goal?

2 Answers2

17

You can achieve that by doing something like this:

local my_string = "hello:hi_there"
local extracted = string.match(my_string, ":(.*)")
print(extracted)

The parentheses do a pattern capture, the dot means any character and the star tells the match function that the pattern should be repeated 0 or more times. It starts matching at the : and takes everything until the end of the string.

Rok
  • 787
  • 9
  • 17
  • i do print(string.match("hello:hi_there:erhuheriu:gg", ":(.*)")) and just need last substring ie gg after : , any hints ? – Altanai Nov 06 '19 at 12:45
  • 3
    @Altanai you can do something like `print(string.match("first:second:third",":([^:]+)$"))`. `[^:]` matches anything that is not `:` and `$` matches the end of the string. – Rok Nov 07 '19 at 13:30
2

Because you don't want the : to be in the selection, I would combine string.find() and string.sub() in the following implementation:

local string = "hello:hi_there"
beg, final = string.find(string, ":") # Returns the index
local new_string = string.sub(string, final + 1) # Takes the position after the colon 

According to the documentation, if you left sub()'s third argument blank, it defaults to -1, so it takes all the remaining string.

RicHincapie
  • 3,275
  • 1
  • 18
  • 30