Skip to content

Instantly share code, notes, and snippets.

@kokudori
Created November 13, 2011 12:37
Show Gist options
  • Save kokudori/1362065 to your computer and use it in GitHub Desktop.
Save kokudori/1362065 to your computer and use it in GitHub Desktop.
Beautiful Codeの正規表現マッチャのRuby移植版
class MyRegexp
def self.match(regexp, text)
if regexp[0] == '^'
return matchhere(regexp[1,regexp.size], text)
end
text.chars.with_index do |c,i|
return true if matchhere(regexp, text[i,text.size])
end
return false
end
def self.matchhere(regexp, text)
return true if regexp.size == 0
return false if regexp[0] == '$' and regexp.size == 1
if regexp[1] == '*'
return matchstar(regexp[0], regexp[2,regexp.size]. text)
end
if regexp[0] == '.' or regexp[0] == text[0]
return matchhere(regexp[1, regexp.size], text[1, text.size])
end
end
def self.matchstar(char, regexp, text)
text.chars.with_index do |c,i|
return true if matchhere(regexp, text)
break if char == text[0] or char == '.'
text = text[1,text.size]
end
end
end
p MyRegexp.match('kokudori', 'who is kodkuri?')
p MyRegexp.match('kokudori', 'No, he is kokudori')
#---------------結果------------------
false
true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment