2016-08-28 4 views
3

私はマークダウンのようなテキストを簡単に解析する方法を作っています。ルビーで空白の改行のみを保存する最良の方法

<p>hello this</p> 
<p>is part of the same paragraph</p> 
<p></p> 
<p>this is a separate paragraph</p> 
<p></p> 
<p></p> 
<p></p> 
<p>this is another one!</p> 
- さんは、私の文字列は、私はこのように見える終わるごとにラインの新しい <p>タグを追加している、今

hello this\n 
is part of the same paragraph\n 
\n 
this is a separate paragraph\n 
\n 
\n 
\n 
this is another one!\n 

(\ n個の示す文字で)このようになりますふりをしてみましょう

ruby​​で.squeeze("\n")メソッドを使用することで、これを少し減らしました。あなたが見ることができるようにそれから私のHTMLはthis-

<p>hello this</p> 
<p>is part of the same paragraph</p> 
<p>this is a separate paragraph</p> 
<p>this is another one!</p> 

ようになり、これは余分なp要素を取り除きます - 最初の2行はまだ段落に分割されているが。

新しい段落が発生するために2つのリターンが必要なマークダウンと同様の効果を得るにはどうすればよいですか?例えば

this is 
part of the same paragraph 

new para! 

<p>this is part of the same paragraph</p> 
<p>new para!</p> 

は、私は多分、忘れてる正規表現解決策はあるの...なる

this is part of the same paragraph 
\n 
new para! 

なり?

答えて

1

ここでは簡単でしょう:

str = <<-STR 
hello this 
is part of the same paragraph 

this is a separate paragraph 



this is another one! 
STR 

result = '' 

result << '<p>' 
result << str.gsub!(/\n{2,}/, "</p>\n<p>") 
result << '</p>' 

puts result 


# Output 
<p>hello this 
is part of the same paragraph</p> 
<p>this is a separate paragraph</p> 
<p>this is another one! 
</p> 
0

あなたはGSUBのブロックバージョンを使用することができます。

str = "hello this 
is part of the same paragraph 

this is a separate paragraph 



this is another one! 
" 

str.gsub!(/\n+/) { |newlines| newlines[/\n{2,}/] ? "\n" : " " } 
str.each_line { |line| puts "<p>#{line.strip}</p>" } 

# output 
<p>hello this is part of the same paragraph</p> 
<p>this is a separate paragraph</p> 
<p>this is another one!</p> 
関連する問題