使用 Lua 中的正则表达式替换字符串

我有很多日志文件,每个文件都包含 1000 多行。 文件的一部分如下:

{@BLOCK|1%r1331|00
{@A-JUM|0|-9.352000E+06{@LIM2|+9.999999E+99|+1.000000E+04}}
}
{@BLOCK|1%x1001_swp|00
{@A-JUM|0|+3.362121E+00{@LIM2|+2.000000E+01|+0.000000E+00}}
}
{@BLOCK|1%x1101_swp|00
{@A-JUM|0|+3.282704E+00{@LIM2|+2.000000E+01|+0.000000E+00}}
}
{@BLOCK|1%x201_swp|00
{@A-JUM|0|+3.276452E+00{@LIM2|+2.000000E+01|+0.000000E+00}}
}
{@BLOCK|1%x202_swp|00
{@A-JUM|0|+3.216571E+00{@LIM2|+2.000000E+01|+0.000000E+00}}
}

我想将第 8 行的“+3.282704E+00”替换为另一个值。重要的是要知道,像“{@BLOCK|1%x1101_swp|00”这样的标记是唯一的,但是该标记的行号可能因文件而异。 如何在 Lua 中实现这一点?我尝试使用正则表达式替换“@BLOCK”和“{@LIM2”之间的两行,但没有结果。 对于:

 {@BLOCK|1%x1101_swp|00
 {@A-JUM|0|+3.282704E+00{@LIM2|+2.000000E+01|+0.000000E+00}}

我尝试了:

if string.match(line,"{@BLOCK%|1%%1101_swp%|00..{@A-JUM%|0%|.............{@LIM2") then
string.gsub(line,"{@A-JUM%|0%|.............{@LIM2", "{@A-JUM%|0%|"..ff[#lines].."{@LIM2")
点赞
用户3832970
用户3832970

你可以使用

local res = line:gsub("(%{@BLOCK%|1%%x201_swp%|00\r?\n%{@A%-JUM%|0%|).-(%{@LIM2%|)", "%1".. ff[$lines] .."%2")

参见Lua演示

详情

  • (%{@BLOCK%|1%%x201_swp%|00\r?\n%{@A%-JUM%|0%|) - 组1:以{@BLOCK|1%x201_swp|00子字符串开头,后跟一个可选的CR符号,然后是LF,然后是{@A-JUM|0|
  • .- - 任何0+个字符,尽可能少
  • (%{@LIM2%|) - 组2:{@LIM2|子字符串。

%1%2占位符分别指的是替换模式中存储在组1和组2中的值。

2018-03-26 19:42:56
用户7504558
用户7504558

你可以使用这种更统一的方式:

local line = [[{@BLOCK|1%r1331|00
{@A-JUM|0|-9.352000E+06{@LIM2|+9.999999E+99|+1.000000E+04}}
}
{@BLOCK|1%x1001_swp|00
{@A-JUM|0|+3.362121E+00{@LIM2|+2.000000E+01|+0.000000E+00}}
}
{@BLOCK|1%x1101_swp|00
{@A-JUM|0|+3.282704E+00{@LIM2|+2.000000E+01|+0.000000E+00}}
}
{@BLOCK|1%x201_swp|00
{@A-JUM|0|+3.276452E+00{@LIM2|+2.000000E+01|+0.000000E+00}}
}
{@BLOCK|1%x202_swp|00
{@A-JUM|0|+3.216571E+00{@LIM2|+2.000000E+01|+0.000000E+00}}
}]]

local function Replace(line, unic_block, unic_num, to_num)
    unic_block = unic_block:gsub("%%","%%%%") -- 转义特殊符号 '%' 
    unic_num = unic_num:gsub("[%+%.]",function(c) return "%"..c end)  -- 转义特殊符号 '+' 和 '.'
    return line:gsub("(" ..unic_block .. ".-%c+.-)" .. unic_num, "%1" .. to_num )
end
local xline = Replace(line, "{@BLOCK|1%x1101_swp|00", "+3.282704E+00", "9999999")

print (xline)
2018-03-26 21:30:31