次の形式で関連する wiki ページにリンクする (gollum) wiki ページのキー フレーズにマークダウンを追加したいと考えています。
This is the key phrase.
なる
This is the [[key phrase|Glossary#key phrase]].
次のようなキーフレーズのリストがあります。
keywords = ["golden retriever", "pomeranian", "cat"]
そしてドキュメント:
Sue has 1 golden retriever. John has two cats.
Jennifer has one pomeranian. Joe has three pomeranians.
すべての行を反復処理して、各キーワードのすべての一致 (まだリンクではない) を見つけたいと考えています。私の現在の試みは次のようになります。
File.foreach(target_file) do |line|
glosses.each do |gloss|
len = gloss.length
# Create the regex. Avoid anything that starts with [
# or (, ends with ] or ), and ignore case.
re = /(?<![\[\(])#{gloss}(?![\]\)])/i
# Find every instance of this gloss on this line.
positions = line.enum_for(:scan, re).map {Regexp.last_match.begin(0) }
positions.each do |pos|
line.insert(pos, "[[")
# +2 because we just inserted 2 ahead.
line.insert(pos+len+2, "|#{page}\##{gloss}]]")
end
end
puts line
end
ただし、同じ行の同じキー フレーズに 2 つの一致がある場合、これは問題になります。行に物を挿入するため、最初の一致以降、各一致で見つけた位置は正確ではありません。毎回挿入のサイズを調整できることは知っていますが、私の挿入は光沢ごとに異なるサイズであるため、最も力ずくでハッキーなソリューションのようです.
毎回任意に調整することなく、同じ行に同時に複数の挿入を行うことができるソリューションはありますか?