2017-07-14 44 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