鉴于此字符串:
bc. some text
more text
even more
^ above here is the empty line
我希望它是:
<pre>
some text
more text
even more
</pre>
^ above here is the empty line
我如何正确使用从bc.
开始直到第一个空行“?
到目前为止,我得到了这个:
# note that for some reason a direct .gsub! behaves
# differently/fails when using the block, so I use .gsub
textile_markup = textile_markup.gsub(/^bc. .*^$/m) { |s| "<pre>#{s[5..(s.length)]}</pre>" }
可以理解的是,这与贪婪直到最后一个空行 - 而不是第一行。 如何让^ $部分非贪婪?
答案 0 :(得分:2)
str =
"bc. some text
more text
even more
^ above here is the empty line
bc. some text
more text
even more
^ above here is the empty line"
puts str.gsub(/^bc\. (.*?)\n\n/m, "<pre>\n\\1\n</pre>\n\n")
输出:
<pre>
some text
more text
even more
</pre>
^ above here is the empty line
<pre>
some text
more text
even more
</pre>
^ above here is the empty line
?
中的 .*?
使得明星运算符非贪婪
/m
修饰符使点匹配换行符
答案 1 :(得分:1)
它可以一次完成,但需要做一些准备:
txt = <<DOC
bc. some text
more text
even more
bc. some text
more text
even more
DOC
TRANSFORMS = {"bc. " => "<pre>\n", # The 'bc. should become <pre> followed by a line-end
/^ / => "", # leading space should be eliminated
"\n\n" => "\n<\/pre>\n\n"} # empty line should be preceded by a closing pre-tag
re = Regexp.union(TRANSFORMS.keys)
puts txt.gsub(re, TRANSFORMS)
输出:
<pre>
some text
more text
even more
</pre>
<pre>
some text
more text
even more
</pre>