Skip to content

Instantly share code, notes, and snippets.

@eduardoarandah
Last active August 3, 2023 19:10
Show Gist options
  • Save eduardoarandah/788ecd6055ad85b49d1d7cbc4cfaf202 to your computer and use it in GitHub Desktop.
Save eduardoarandah/788ecd6055ad85b49d1d7cbc4cfaf202 to your computer and use it in GitHub Desktop.
Neovim, complex replacement in lua
-- GOAL: replace placeholders with values
--
-- FIELDS EXAMPLE:
-- title,text,link
-- hello,world,something.com
-- good,morning,example.com
-- another,line,asdf.com
-- last,line,asdf.com
--
-- PATTERN EXAMPLE:
-- (placeholders and headers must match. example: title, text, link)
-- <h1>title</h1> <p>text</p> <a href="link">read more</a>
--
-- OUTPUT EXAMPLE:
-- <h1>hello</h1> <p>world</p> <a href="something.com">read more</a>
-- <h1>good</h1> <p>morning</p> <a href="example.com">read more</a>
-- <h1>another</h1> <p>line</p> <a href="asdf.com">read more</a>
-- <h1>last</h1> <p>line</p> <a href="asdf.com">read more</a>
-- subsitutes multiple strings
local function multiple_substitution(layout, searches, replacements)
local outputString = layout
for i, v in ipairs(searches) do
outputString = string.gsub(outputString, v, replacements[i])
end
return outputString
end
-- splits a string into a table by a separator
local function split_string(inputstr, separator)
separator = separator or "%s" -- default
local t = {}
for str in string.gmatch(inputstr, "([^" .. separator .. "]+)") do
table.insert(t, str)
end
return t
end
-- performs complex replacement, first line in fields are headers, and must match the placerholders in pattern
local function complex_replace(fields, pattern)
local headers
local body = {}
-- step 1: get headers and body in fields
-- Iterate over non-empty lines in the string using string.gmatch
for line in fields:gmatch("[^\r\n]+") do
-- non empty lines
if line:match("%S") then
-- fist is headers, else is body
if headers == nil then
headers = split_string(line, ",")
else
body[#body + 1] = split_string(line, ",")
end
end
end
-- perform substitution on pattern on each row in body
for i, replacements in ipairs(body) do
body[i] = multiple_substitution(pattern, headers, replacements)
end
return body
end
local fields = [[
title,text,link
hello,world,something.com
good,morning,example.com
another,line,asdf.com
last,line,asdf.com
]]
local pattern = '<h1>title</h1> <p>text</p> <a href="link">read more</a>'
local result = complex_replace(fields, pattern)
for _, v in ipairs(result) do
print(v)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment