B
B
Begetan2012-05-03 22:23:50
Programming
Begetan, 2012-05-03 22:23:50

How to write a parser in LUA?

The task is to write a function for fast thinning of a text file in Lua.
html or javascript file. At the input we have string. You need to thin out a large block, for example like this:

function lua_filter_bloсk ("<-- Great work begin -->","<--Great work done-->","Shit happens")

Essentially, you need a function that simply looks for start and stop and replaces all text between fragments with replace. In PHP, this function might look like this:
function subs_filter_block ($start, $stop, $replace) {
        global $result;
        $start_pos = stripos ($result, $start);
        if ($start_pos !== false) {
                $end_pos = stripos($result, $stop);
                if (($end_pos !== false) && ($start_pos < $end_pos)) {
                        $result =substr_replace ($result, $replace, $start_pos, ($end_pos - $start_pos + strlen($stop)));
                }
        }
        return;
}

Now we need to do it in Lua. For educational purposes, two extreme options are of interest - as simple as possible and as quickly as possible. Should the data be treated as a string? Is it worth converting to a table? How?
The ideal completion would be a ready reference to a library function. Unfortunately, the quality and relevance of the Lua documentation does not even allow you to quickly find out if there is a desired function or library. Interesting options I would be willing to test for performance.
UPDATE 1. The first two who responded did not give a working solution, but forced them to conduct tests and read the manual about patterns (not to be confused with regexp !)
As a result, we got the following version of the working code:
function subs_filter_block(startWord, endWord, replaceStr)
  res = res:gsub(startWord .. "(.-)" .. endWord, replaceStr);
end

It remains to understand how fast Lua patterns work.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Mikhail Osher, 2012-05-04
@miraage

As far as I know, there is no non-exciting search, but in theory it should work :)

testStr = "Hello Johny !";

function do_replace(inputStr, startWord, endWord, replaceStr)
  return string.gsub(inputStr, startWord .. " (%S+) " .. endWord, startWord .. " " .. replaceStr .. " " .. endWord);
end

result = do_replace(testStr, "Hello", "!", "habrahabr");
print(result);

S
Sergey Lerg, 2012-05-04
@Lerg

Can be done using string.gsub. Something like string.gsub(givenString, start… '(.*)'… stop, replace)
This is in regex.
You can make the equivalent of the php code using the corresponding functions from the string module.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question