Finding a pair of quotation marks in a string, and getting the substring between them?

Not exactly quotation marks, but I simply want to search for a pair of any single or series of characters, get the substring, and print it out. I wanted it so that any string can be used to find a substring of a string, not just quotation marks. For example, I want to search for a pair of !!'s in a string like This is a !!WARNING!!. I want to print only WARNING while being able to use the same code on different strings without even changing the code itself.

I do have a solution in mind, but it seems to be way too much code. Is this the right solution, or is there a better way to do this?

local String = "I want to get ``this`` part."
local Indicator = "``"

local Part1_Start, Part1_End = string.find(String, Indicator)
local Part2 = if Part1_End then string.find(String, Indicator, Part1_End) elseif Part1_Start then string.find(String, Indicator , Part1_Start) else nil

if (Part1_End or Part1_Start) and Part2 then
	print(String:sub((Part1_End or Part1_Start) + 1, Part2 - 1))
end

I haven’t done string patterns in a while, but this pattern could work.

local String = "Something ``Cool``"
local Indicator = "``"
local Result = String:match(Indicator .. "[%w%s]+" .. Indicator)
if Result then Result = Result:gsub(Indicator, "") end
print(Result) --> Cool? Hopefully.

Learn more about string patterns here: String Patterns

1 Like

The code almost works, the Indicators just have to be removed since they are still there. Do I simply use string.sub() at this point?

Scratch that, I just noticed you edited the post. Yes, it does work. Thanks!

1 Like

Actually I change the code to fix this problem. You would use gsub to replace the text using a pattern. In this case there is no pattern, it is just the indicator.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.