Home > Mobile >  How to find the words after a space?
How to find the words after a space?

Time:04-03

I would like, to know in lua, how can we do that :

local test = "Hey Hello World"
local extract = string.match(test, "I don't know what to put here")
print(extract)

Result = Hello World

I tried with

local test = "Hey Hello World"
local extract = string.match(test, "^.*%s(.*)")
print(extract)

But the result = "World"

CodePudding user response:

local test = "Hey Hello World"
local extract = string.match(test, "^.*%s(.*)")
print(extract)

is almost correct, but somewhat overcomplicated. The result is just "World" because it won't get everything after the first, but rather everything after the last space because the first .* is greedy - it will match as much as it can. Your pattern could be fixed if you just used .- instead, which will match as few characters as possible: "^.-%s(.*)" yields the desired result.

Your pattern can however be simplified significantly by just omitting the ^ beginning pattern anchor as Lua patterns always go from left-to-right and (.*) will be a greedy match to the end: "%s(.*)" will provide you the string after the first space character (can be empty). If you want to allow double spaces, you have to use a quantifier for the first spacing: "%s (.*)".

lhf's pattern " (. )" is also an option, assuming a simple ASCII space and assuming that you want the returned match to be a nonempty string or nil.

  • Related