2017-07-14 91 views
2

我想修改我的网址是干净和友好的多occurances通过去除特定字符的Lua GSUB正则表达式来替换字符

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) 

出现了多次,我想什么来实现输出为这样的:

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

但是,相反我的输出是这样的:

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

是GSUB日我应该这样做吗?

+0

'URL =网址::GSUB( “([+/=?])%1”, “\ 0%0”):GSUB(下面的代码通过调用gsub一次为每个字符执行此“(。)%z%1”,“”):gsub(“%z(。)%1%1”,“%1”):gsub(“%z。”,“”)' –

回答

2

我不明白如何与一个调用gsub做到这一点。

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,"+/=&?")) 
+0

感谢它的工作原理非常好,并且非常容易实现,并为我所需的内容添加更多字符。 – C0nw0nk

+0

你只需要小心某些字符。例如,一个点不能使用,因为它会匹配所有(。+)。你应该逃避所有的标点符号。我会写它像这样:'函数fix_url(S,C)对于C用C 本地米 :( '')gmatch做 M = C 如果米:匹配 '%W' 则m = '%' ..m结束 s = s:gsub(m ..'+',c) 结束 返回s 结束 ' – tonypdmtr

1

这里是一个可能的解决方案(与任何字符类你喜欢的替换%P):

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) 
+0

非常感谢: )提供的两种解决方案都非常棒,但我将上面的标记标记为答案,因为它更容易用于我需要的内容<3 – C0nw0nk