Created
March 11, 2018 15:40
-
-
Save aleclarson/47bbf17cf78e3e1d0c95220d382e746e to your computer and use it in GitHub Desktop.
Search each line for a pattern
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Search for pattern on each line. | |
search_lines = (str, pattern) -> | |
line = str\find '\n' | |
if line == nil | |
i = 0 | |
return -> | |
if i ~= nil | |
h, i, match = str\find '^'..pattern, i | |
return h, i, match if h ~= nil | |
else | |
h, i, mid, match = 0, 1 | |
return -> | |
-- First line first. | |
if h == 0 | |
h, i, match = str\find "^#{pattern}\n" | |
return h, i, match if h ~= nil | |
h = 1 | |
-- Check if string is 3+ lines. | |
if h == 1 | |
line = str\find '\n', line + 1 | |
mid = "\n#{pattern}\n" if line ~= nil | |
-- Middle lines next. | |
if mid ~= nil | |
h, i, match = str\find p, i | |
return h, i, match if h ~= nil | |
mid = nil | |
-- Last line last. | |
if h ~= -1 | |
h = -1 | |
return str\find "\n#{pattern}$", i |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The
captured
variable only exists if()
is used in the pattern.You cannot use
()
more than once in the pattern.