How to get string (multi word) between characters

Viewed 57

Hello I am trying to get a string between two parentheses

str = "Reason = Failed to connect ( Nickname: Mc Gee ), Banned by: Andrew"

I want to only get Nickname: Mc Gee

I have looked everywhere but all the answers I have seen are for single worded strings and don't work with ()

3 Answers

You can use %b pattern that allows to specify brackets you want to match:

str = "Reason = Failed to connect ( Nickname: Mc Gee ), Banned by: Andrew"
print(str:match("%b()"):gsub("[()]","")) -- prints ` Nickname: Mc Gee `

Also

str = "Reason = Failed to connect ( Nickname: Mc Gee ), Banned by: Andrew"
print(str:match("%((.-)%)"))

There is a complicated answer:

local str = "Reason = Failed to connect ( Nickname: Mc Gee ), Banned by: Andrew"
print(string.match(str, "Reason = [%a%s]+%([%a%s]+:%s+(.*)%s+%).*"))
-- Mc Gee

Hope it's useful~

Related