2010-01-17 15:58:44 -05:00
|
|
|
# Beautiful Code, Chapter 1.
|
|
|
|
# Implements a regular expression matcher that supports character matches,
|
2010-01-17 15:36:46 -05:00
|
|
|
# '.', '^', '$', and '*'.
|
|
|
|
|
|
|
|
# Search for the regexp anywhere in the text.
|
2010-07-29 00:03:42 -04:00
|
|
|
match = (regexp, text) ->
|
2010-01-17 15:36:46 -05:00
|
|
|
return match_here(regexp.slice(1), text) if regexp[0] is '^'
|
|
|
|
while text
|
|
|
|
return true if match_here(regexp, text)
|
2010-07-29 00:03:42 -04:00
|
|
|
text = text.slice(1)
|
2010-01-17 15:36:46 -05:00
|
|
|
false
|
|
|
|
|
|
|
|
# Search for the regexp at the beginning of the text.
|
2010-07-29 00:03:42 -04:00
|
|
|
match_here = (regexp, text) ->
|
|
|
|
[cur, next] = [regexp[0], regexp[1]]
|
2010-01-17 15:36:46 -05:00
|
|
|
if regexp.length is 0 then return true
|
|
|
|
if next is '*' then return match_star(cur, regexp.slice(2), text)
|
|
|
|
if cur is '$' and not next then return text.length is 0
|
|
|
|
if text and (cur is '.' or cur is text[0]) then return match_here(regexp.slice(1), text.slice(1))
|
|
|
|
false
|
|
|
|
|
|
|
|
# Search for a kleene star match at the beginning of the text.
|
2010-07-29 00:03:42 -04:00
|
|
|
match_star = (c, regexp, text) ->
|
2010-06-12 12:15:53 -04:00
|
|
|
loop
|
2010-01-17 15:36:46 -05:00
|
|
|
return true if match_here(regexp, text)
|
|
|
|
return false unless text and (text[0] is c or c is '.')
|
2010-07-29 00:03:42 -04:00
|
|
|
text = text.slice(1)
|
2010-01-17 15:36:46 -05:00
|
|
|
|
2010-10-24 12:48:42 -04:00
|
|
|
console.log match("ex", "some text")
|
|
|
|
console.log match("s..t", "spit")
|
|
|
|
console.log match("^..t", "buttercup")
|
|
|
|
console.log match("i..$", "cherries")
|
|
|
|
console.log match("o*m", "vrooooommm!")
|
2015-09-03 13:20:12 -04:00
|
|
|
console.log match("^hel*o$", "hellllllo")
|