如果你使用一个简单的标记器,管理这类事情会容易得多。一种方法是创建一个可以捕获整个语法的单个正则表达式,但这可能会被证明是有问题的。另一种方法是将文档分为需要重写的部分和应该跳过的部分,这可能是这里更容易的方法。
这里有一个简单的框架,你可以根据需要进行扩展:
def wiki_subst(string)
buffer = string.dup
result = ''
while (m = buffer.match(/<\s*nowiki\s*>.*?<\s*\/\s*nowiki\s*>/i))
result << yield(m.pre_match)
result << m.to_s
buffer = m.post_match
end
result << yield(buffer)
result
end
example = "replace me<nowiki>but not me</nowiki>replace me too<NOWIKI>but not me either</nowiki>and me"
puts wiki_subst(example) { |s| s.upcase }
# => REPLACE ME<nowiki>but not me</nowiki>REPLACE ME TOO<NOWIKI>but not me either</nowiki>AND ME