Question With string patterns

Trying to work out how to apply a gsub rule which affects the input, and everything after it.,

Example:

Input >> LolMyNameXXisLuaBearyGood

With ‘XX’ being the input argument

For this to then output LolMyNameHiXXisLuaBearyGoodHi

1 Like
local MyOutput = nil
local text = "LolMyNameXXisLuaBearyGood"
local done = false

for i = 1,#text-1,1 do
    if done then return end
    if string.sub(text,i,i+1) == ("XX" or "Xx" or "xX" or "xx") then
        done = true
        MyOutput = string.sub(text,1,i-1).."Hi"..string.sub(text,i,#text).."Hi"
        print(output)
    end
end

Thanks for the solution, and while im sure its valid im really specifically looking for a general gsub rule using string patterns, ive come close but finding a magic character / combination for ‘rest of string’ has stumped me.

Can you put @kjetl15 reply as the solution? So we know it’s been solved.

Please read my last response to this post, my issue specifically is yet to be solved.

just do

local myString = "LolMyNameXXisLuaBearyGood"

local newString = myString:gsub("XX", "Hi")

That will just replace the term ‘XX’ with ‘Hi’

local t = "LolMyNameXXisLuaBearyGood"; 
local add = "Hi";  
local input = "XX"
print(t:gsub("(.*)"..input.."(.*)","%1"..add..input.."%2"..add))
--Output-> LolMyNameHiXXisLuaBearyGoodHi
2 Likes
local text = "LolMyNameXXisLuaBearyGood"
local pattern = "XX"
local add = "Hi"

local newString = text:gsub(pattern , add..pattern)..add

output: “LolMyNameHiXXisLuaBearyGoodHi
if the input doesn’t have XX in it it might still give an output with “Hi” at the end, I don’t have a current solution to that right now. As I wrote this theoretically.

Keep in mind if XX is at the beginning or end of the string, this won’t work properly. Depending on the usecase, it may be safer to use (.*) there instead. (+ matches 1 or more characters greedily, while * matches 0 or more characters greedily)

4 Likes

Ended up going with @kjelt15’s solution with an additional match check to make sure the pattern was present to avoid the pointless ‘hi’ at the end.

@addictedroblox1414’s solution does theoretically work but (.+) really screwed up more specific use cases and therefor only worked not he example string, depending on your use case his will work too.

1 Like

Oof that’s right, an honest oversight. Thanks! Will make the appropriate edit.

1 Like

I’m glad you have found your answer!
With @rogchamp edit, the pattern i commented should now be more useful in broader scenarios. Happy coding!

1 Like