Lua - getting all after word

Viewed 119

There is if statement like this: if( reciewed_message == "video " ) then

I need to get all text after 'video' into a string.

For example, for string reciewed_message == "video some music video" i need to get some music video from reciewed_message to use as parameter to search

2 Answers

Use string.match with captures:

s="video some music video"
print(s:match("video (.*)$"))

You can use string.find followed by a string.sub.

string.find searches the string, and finds the starting and end position of the first query that it is given. string.sub returns a sub-string of your string from the position that you require it to.

local received_message = "video some music video"
local query = "video"

-- First parameter is the starting position, we actually want the position that our word ends at, so we ignore the start position by '_'.
local _, len = string.find(received_message, query)

-- Sub-string is zero indexed, so we must add 1 to our length.
local search = string.sub(received_message, len + 1)

print(search)

You can also create a function so it will be easier to use it multiple times.

function search_query(message, query)
    local _, len = string.find(message, query)

    return string.sub(message, len + 1)
end

-- Usage:
print(search_query("video some music video", "video"))

Related