Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How do I replace only 1 match?

I'm trying to make a "Find in page" feature, like the one in Google but it's for a string. I tried to use string.gsub(), but it replaced all the matches.

How can I make it so that it only removes 1 match?

Code so far:

local s = "this is a text string"

local function find(s, matchingString)
   s = s:lower()
   matchingString = matchingString:lower()
   local _, matches = string.gsub(s, matchingString, matchingString)
   if matches == 1 then
      after = " match"
   elseif matchingString == "" then
      print("0 matches")
      return
   else
      after = " matches"
   end

   print(matches..after)
   
   if matches > 0 then
      for i = 1, matches do
         local a, b = s:find(matchingString)
         s = s:gsub(matchingString, "")--what can I change this to so that it only removes 1 match
         print(s)
         print("Location of match "..i..": "..a..", "..b)
      end
   end   
end

find(s, "a")

1 answer

✓ Accepted answer

string.gsub has fourth argument which lets you specify max amount of matches to replace, if you put 1 there it will only replace the first match

local s = "that is a text string"
local Result = string.gsub(s, "a", "*", 1)
print(Result)

th*t is a text string

local s = "that is a text string"
local Result = string.gsub(s, "a", "*", 2)
print(Result)

th*t is * text string

I however do not understand why don't you just use string.find as you did in your function, it will also return position of the match if you need it

local s = "that is a text string"
local Start, End = string.find(s, "a")
print(Start, End)

3 3

here it returned 3 because first a starts at 3 and ends at it. When you have the position of the letter you can just remove it with string.sub.

1 comment

1

Thank you! I looked on the dev hub and it only had 3 arguments. They should update it

This discussion is preserved as it was. New answers, comments, and votes are closed.