我如何更改字串中匹配的所有內容而不更改非匹配項?
local a = "\" Hello World! I want to replace this with a bytecoded version of this!\" but not this!"
for i in string.gmatch(a, "\".*\"") do
print(i)
end
例如,我要"\"Hello World!\" Don't Replace this!"到"\"\72\101\108\108\111\32\87\111\114\108\100\33\" Don't Replace this!"
uj5u.com熱心網友回復:
你的問題有點棘手,因為它可能涉及:
- Lua 模式
string.gsub功能- 訪問字串的位元組
string.byte - 字串連接
table.concat
首先,如果您需要實作Lua模式,請知道有一個非常方便的Lua語法,非常適合處理帶引號的字串。使用此語法,不是使用雙引號打開/關閉字串,而是使用字符[[和]]. 關鍵區別在于,在這些標記之間,您不必再轉義參考的字串了!
String = [["Hello World!" Don't Replace this!]]
然后,我們需要構建正確的Lua模式,一種可能性是匹配雙引號 ( ") 然后匹配所有不是雙引號 ( ")的字符,這給了我們以下模式:
[["([^"] )"]]
| **** |
| \-> the expression to match
| |
quote quote
那么我們研究一下這個函式string.gsub,我們可以了解到,callback當匹配到一個模式時,該函式可以呼叫a ,匹配的字串會被回呼的回傳值替換。
function ConvertToByteString (MatchedString)
local ByteStrings = {}
local Len = #MatchedString
ByteStrings[#ByteStrings 1] = [[\"]]
for Index = 1, Len do
local Byte = MatchedString:byte(Index)
ByteStrings[#ByteStrings 1] = string.format([[\%d]], Byte)
end
ByteStrings[#ByteStrings 1] = [[\"]]
return table.concat(ByteStrings)
end
在這個中function,我們遍歷匹配字串的所有字符。然后對于每個字符,我們使用函式提取其位元組值并使用函式string.byte將其轉換為字串 string.format。我們把這個字串放在一個臨時陣列中,我們將在函式的末尾連接它。
將子字串連接成更大字串的函式是table.concat. 這是一個非常方便的功能,可以如下使用:
> table.concat({ [[\10]], [[\11]], [[\12]] })
\10\11\12
我們需要做的剩下的事情就是測驗這個出色的功能:
> String = [["Hello World!" Don't Replace this!]]
> NewString = String:gsub([["([^"] )"]], ConvertToByteString)
> NewString
\"\72\101\108\108\111\32\87\111\114\108\100\33\" Don't Replace this!
uj5u.com熱心網友回復:
你需要string.gsub。
local a = "\"Hello World!\" Don't Replace this!"
local function convert(str)
local byte_str = ""
for i = 1, #str do
byte_str = byte_str .. "\\" .. tostring(string.byte(str, i))
end
return byte_str
end
a = string.gsub(a, "\"(.*)\"", function(matched_str)
return "\"" .. convert(matched_str) .. "\""
end)
print(a)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/366477.html
下一篇:'subscript(_:)'不可用:不能用Int下標String,在swift中使用String.Index代替
