Created
October 16, 2014 11:02
-
-
Save ochaochaocha3/f10a5aaed66764f8c0a9 to your computer and use it in GitHub Desktop.
IRC 風構文解析
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'strscan' | |
module Converter | |
AVAILABLE_TAGS = { | |
/<bold>/ => { | |
start_tag: '<b>', | |
end_tag: '</b>' | |
}, | |
/<underline>/ => { | |
start_tag: '<u>', | |
end_tag: '</u>' | |
} | |
} | |
STOP_TAG = /<stop>/ | |
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 | |
s_good = 'foo<bold>bar<underline>baz<stop>qux' | |
print("#{s_good} -> ") | |
puts(Converter.convert(s_good)) | |
begin | |
s_bad = 'foo<bold>bar<underline>baz' | |
print("#{s_bad} -> ") | |
puts(Converter.convert(s_bad)) | |
rescue => e | |
puts(e) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment