Skip to content

Instantly share code, notes, and snippets.

@aleclarson
Created March 11, 2018 15:40
Show Gist options
  • Save aleclarson/47bbf17cf78e3e1d0c95220d382e746e to your computer and use it in GitHub Desktop.
Save aleclarson/47bbf17cf78e3e1d0c95220d382e746e to your computer and use it in GitHub Desktop.
Search each line for a pattern
-- 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
@aleclarson
Copy link
Author

aleclarson commented Mar 11, 2018

for startIndex, endIndex, captured in search_lines(input, pattern)
  print startIndex, endIndex, captured

The captured variable only exists if () is used in the pattern.

You cannot use () more than once in the pattern.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment