0

给定这个字符串:

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>" }

可以理解,这匹配贪婪,直到最后一个空行 - 而不是第一个空行。 如何使 ^$ 部分不贪婪?

4

2 回答 2

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

解释

?in.*?使星号算子不贪心

/m最后修饰符使点匹配换行符

于 2013-03-20T03:28:29.353 回答
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>
于 2013-03-19T22:09:05.450 回答