C0nw0nk
C0nw0nk

Reputation: 960

Lua gsub regex to replace multiple occurances of characters

I am trying to modify my URL to be clean and friendly by removing more than one occurrence of specific characters

local function fix_url(str)
return str:gsub("[+/=]", {["+"] = "+", ["/"] = "/", ["="] = "="}) --Needs some regex to remove multiple occurances of characters
end
url = "///index.php????page====about&&&lol===you"
output = fix_url(url)

What I would like to achieve the output as is this :

"/index.php?page=about&lol=you"

But instead my output is this :

"///index.php????page====about&&&lol===you"

Is gsub the way i should be doing this ?

Upvotes: 2

Views: 1361

Answers (2)

lhf
lhf

Reputation: 72312

I don't see how to do this with one call to gsub. The code below does this by calling gsub once for each character:

url = "///index.php????page====about&&&lol===you"

function fix_url(s,C)
    for c in C:gmatch(".") do
        s=s:gsub(c.."+",c)
    end
    return s
end

print(fix_url(url,"+/=&?"))

Upvotes: 4

tonypdmtr
tonypdmtr

Reputation: 3225

Here's one possible solution (replace %p with whatever character class you like):

local
function fold(s)
  local ans = ''
  for s in s:gmatch '.' do
    if s ~= ans:sub(-1) then ans = ans .. s end
  end
  return ans
end

local
function fix_url(s)
  return s:gsub('%p+',fold) --remove multiple same characters
end

url = '///index.php????page====about&&&lol===you'
output = fix_url(url)

print(output)

Upvotes: 1

Related Questions