Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua Match Everything After Character in String

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?

like image 473
Christian Sirolli Avatar asked May 17 '18 16:05

Christian Sirolli


People also ask

How do I match a string in Lua?

> = string. match("foo 123 bar", '%d%d%d') -- %d matches a digit 123 > = string. match("text with an Uppercase letter", '%u') -- %u matches an uppercase letter U. Making the letter after the % uppercase inverts the class, so %D will match all non-digit characters.

How do you use %s in Lua?

The % is also used to designate a character class in the pattern syntax used with some string functions. Show activity on this post. Lua uses %s in patterns (Lua's version of regular expressions) to mean "whitespace". %s+ means "one or more whitespace characters".

What does GSUB do in Lua?

gsub() function has three arguments, the first is the subject string, in which we are trying to replace a substring to another substring, the second argument is the pattern that we want to replace in the given string, and the third argument is the string from which we want to replace the pattern.

What is %w Lua?

Valid in Lua, where %w is (almost) the equivalent of \w in other languages. ^[%w-.]+$ means match a string that is entirely composed of alphanumeric characters (letters and digits), dashes or dots.


2 Answers

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.

like image 196
Rok Avatar answered Sep 17 '22 10:09

Rok


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.

like image 32
RicarHincapie Avatar answered Sep 19 '22 10:09

RicarHincapie