在Ruby中解析和替换标记
我想解析一个简单的字符串,如:在Ruby中解析和替换标记,ruby,regex,Ruby,Regex,我想解析一个简单的字符串,如: "My name is **NAME**" to "My name is <strong>NAME</strong\>" 注: 无法使用任何外部宝石,即使降价宝石可能已经完成了任务。 如果我理解正确的话,应该很简单: text = "My name is **NAME**" => "My name is **NAME**" text = text.gsub(([a-zA-Z\s]*)(\*\*)([a-zA-Z\s]*)(\*\*)
"My name is **NAME**" to "My name is <strong>NAME</strong\>"
注:
无法使用任何外部宝石,即使降价宝石可能已经完成了任务。
如果我理解正确的话,应该很简单:
text = "My name is **NAME**"
=> "My name is **NAME**"
text = text.gsub(([a-zA-Z\s]*)(\*\*)([a-zA-Z\s]*)(\*\*)/,"\\1<strong>\\3</strong>")
=> "My name is <strong>NAME</strong>"
我已经用这个命令text在irb中测试了它。gsub[a-zA-Z\s]*\\*\*[a-zA-Z\s]*\*\*\*/,\\1\\3
更新的如果您希望处理更多的案例,请考虑以下事项:
class SurroundMarkup
def initialize(markup_map: {})
@markup_map = markup_map
end
def format(text)
text.tap do |formatted_text|
@markup_map.each do |markup, tag|
formatted_text.gsub!(/#{markup}(?<text>.*?)#{markup}/) do |m|
start_tag(tag) + $~[:text] + stop_tag(tag)
end
end
end
end
private
def start_tag(tag)
"<#{tag}>"
end
def stop_tag(tag)
"</#{tag}>"
end
end
您可以按如下方式使用:
markup_map = {
/\*\*/ => "strong",
/\*/ => "i",
}
s = SurroundMarkup.new(markup_map: markup_map)
s.format("My name is **NAME**") #=> "My name is <strong>NAME</strong>"
s.format("*Ruby* is cool") #=> "<i>Ruby</i> is cool"
这无法正确处理结束标记。i、 它把文本的两面都加粗。你为什么要自己实施这个呢?