i want to know how to get text form a particular part of a text this is what i mean like 'hello (new text)' in the brackets it says 'new text' and i want to print the text only in the brackets for my case its 'new text'
local text= "hello (new text) test" local text2 = text:split("(") local text3 = text2[2]:split(")") print(text3[1])
There is more simple but more complicated way, it takes only 1 line, that is string.match
, you need to use string patterns which might be complicated at first but they are quite simple, here is what will get text in the bracket
local text = 'hello (new text)' local result = string.match(text, '%((.-)%)') print('the result is: ' .. result)
The pattern is %((.-)%)
, the reason why you have %
before ()
is because these symbols are used in string formatting so doing
local text = '(((((' string.match(text, '%(') -- returns first bracket ( string.match(text, '(') -- error
That is why both brackets have %
before them, to match the text and not use them as a pattern. This will match the brackets but we to match content of the brackets, %S+
is a pattern that matches all the characters but in this case it's .
(which also matches all except it priorities on .
letter too but not in this case) because you can't put -
after a +
, the second brackets there are used as a pattern, if you would do %(.-%)
, nothing would work.