Skip to content

Instantly share code, notes, and snippets.

@ochaochaocha3
Last active August 29, 2015 14:08
Show Gist options
  • Save ochaochaocha3/ac2208c4bc46e2b2d756 to your computer and use it in GitHub Desktop.
Save ochaochaocha3/ac2208c4bc46e2b2d756 to your computer and use it in GitHub Desktop.
IRC 発言内容構文解析
# vim: fileencoding=utf-8
require 'strscan'
module Converter
AVAILABLE_TAGS = {
/\u0002/ => {
start_tag: '<b>',
end_tag: '</b>'
},
/\u001f/ => {
start_tag: '<u>',
end_tag: '</u>'
}
}
STOP_TAG = /\u000f/
def convert(source)
scanner = StringScanner.new(source)
opened_tags = []
result = ''
until scanner.eos?
if scanner.scan(STOP_TAG)
until opened_tags.empty?
tag = opened_tags.pop
result << tag[:end_tag]
end
next
end
AVAILABLE_TAGS.each do |pattern, tag|
if scanner.scan(pattern)
result << tag[:start_tag]
opened_tags.push(tag)
next
end
end
result << scanner.getch
end
raise 'opened tags remain' until opened_tags.empty?
result
end
module_function :convert
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment