Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How to print text form a particular part of a text?

Asked by 3 years ago
Edited 3 years ago

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'

0
I don't understand this that much as I can't read it. vincentthecat1 199 — 3y
0
i will try to improve it Retallack445 75 — 3y

2 answers

Log in to vote
0
Answered by 3 years ago
local text= "hello (new text) test"

local text2 = text:split("(")
local text3 = text2[2]:split(")")
print(text3[1])
Ad
Log in to vote
0
Answered by
imKirda 4491 Moderation Voter Community Moderator
3 years ago
Edited 3 years ago

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.

Answer this question