我想了解lpeg如果字串不在某個開始和結束分隔符之間,我該如何替換它們。下面是一個示例,我想在其中使用SKIPstart并SKIPstop表示不應替換文本的位置。
rep
rep
SKIPstart
rep
rep
SKIPstop
rep
rep
到
new
new
SKIPstart
rep
rep
SKIPstop
new
new
這是另一個帶有多個分隔符的示例:
rep
rep
SKIPstart
rep
rep
SKIPstop
rep
rep
SKIPstart
rep
rep
SKIPstop
到
new
new
SKIPstart
rep
rep
SKIPstop
new
new
SKIPstart
rep
rep
SKIPstop
并嵌套
rep
rep
SKIPstart
rep
SKIPstart
rep
SKIPstop
rep
SKIPstop
rep
rep
到
new
new
SKIPstart
rep
SKIPstart
rep
SKIPstop
rep
SKIPstop
new
new
uj5u.com熱心網友回復:
抱歉,我不知道 lpeg,但你的任務很容易用通常的 Lua 模式解決。
IMO、lpeg 或其他外部正則運算式庫在大多數情況下都過大了,Lua 模式出奇地足夠好。
local s = [[
rep
rep
SKIPstart
rep
rep
SKIPstop
rep
rep
SKIPstart
rep
SKIPstart
rep
SKIPstop
rep
SKIPstop
rep
rep
]]
s = s:gsub("SKIPstart", "\1%0")
:gsub("SKIPstop", "%0\2")
:gsub("%b\1\2", "\0%0\0")
:gsub("(%Z*)%z?(%Z*)%z?",
function(a, b) return a:gsub("rep", "new")..b:gsub("[\1\2]", "") end)
print(s)
輸出:
new
new
SKIPstart
rep
rep
SKIPstop
new
new
SKIPstart
rep
SKIPstart
rep
SKIPstop
rep
SKIPstop
new
new
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/386002.html
