How can I check if there's an opening '(' and a closing ')'

Let’s say I have a string,

"text (and more text)"

How can I check, if there’s an opening parenthesis and a closing parenthesis, get the text between, but if there’s only an opening, do something else.

1 Like

There is functions for that built-in

I know what a string is. I need to get the text between.

local String = "text (and more text)"

print(string.match(String, "%((.-)%)"))
1 Like

What do you need to use this for? That would help people make a better answer.

May I suggest next time explaining how it works then just giving them the code so they and others have a chance to learn from this post.

Lets not forget that %b was made for this :scream_cat:

local String = "text (and more text)"

print(string.match(String, "%b()"))

And extending this we can make an iterator:

local String = "text (and more text) (and more and more)"

local Reader = string.gmatch(String, "%b()")

for Capture in Reader do
    print(Capture)
end

didn’t use %b() because it keeps the parenthesis in there
I have some code down below showing how both of the patterns would work

Code
local String = "text (and more text) (and more and more)"

-- using %b()
for Capture in string.gmatch(String, "%b()") do
    Capture = string.sub(Capture, 2, -2)

    print(Capture)
end

-- without using %b()
for Capture in string.gmatch(String, "%((.-)%)") do
    print(Capture)
end
--output
and more text
and more and more
and more text
and more and more

I made a slight change to my string pattern
replaced the .* with .-

EDIT:
my original reply should have .- in the string pattern now

1 Like