PageRenderTime 27ms CodeModel.GetById 20ms app.highlight 4ms RepoModel.GetById 2ms app.codeStats 0ms

/examples/beautiful_code/regular_expression_matcher.coffee

http://github.com/jashkenas/coffee-script
CoffeeScript | 34 lines | 24 code | 4 blank | 6 comment | 8 complexity | ce36fbefe16ce4b69c99e56fb47e140e MD5 | raw file
 1# Beautiful Code, Chapter 1.
 2# Implements a regular expression matcher that supports character matches,
 3# '.', '^', '$', and '*'.
 4
 5# Search for the regexp anywhere in the text.
 6match = (regexp, text) ->
 7  return match_here(regexp.slice(1), text) if regexp[0] is '^'
 8  while text
 9    return true if match_here(regexp, text)
10    text = text.slice(1)
11  false
12
13# Search for the regexp at the beginning of the text.
14match_here = (regexp, text) ->
15  [cur, next] = [regexp[0], regexp[1]]
16  if regexp.length is 0 then return true
17  if next is '*' then return match_star(cur, regexp.slice(2), text)
18  if cur is '$' and not next then return text.length is 0
19  if text and (cur is '.' or cur is text[0]) then return match_here(regexp.slice(1), text.slice(1))
20  false
21
22# Search for a kleene star match at the beginning of the text.
23match_star = (c, regexp, text) ->
24  loop
25    return true if match_here(regexp, text)
26    return false unless text and (text[0] is c or c is '.')
27    text = text.slice(1)
28
29console.log match("ex", "some text")
30console.log match("s..t", "spit")
31console.log match("^..t", "buttercup")
32console.log match("i..$", "cherries")
33console.log match("o*m", "vrooooommm!")
34console.log match("^hel*o$", "hellllllo")