55
42

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

改行っぽいものすべてにマッチする正規表現

Posted at

こんな改行コードがばらばらなテキストがあったとき、

str = "A\r\nB\rC\nD"

いままで次のようにがんばってマッチさせていましたが、

str.gsub(/\r\n|\r|\n/, "<br/>")     # => "A<br/>B<br/>C<br/>D"

\R だけでよかったと知りました。

str.gsub(/\R/, "<br/>")             # => "A<br/>B<br/>C<br/>D"

\R は、広い範囲で、改行になる文字すべてにマッチしてくれるので、<br/> に変換したい場合などはなおさら \R でいいように思いました。

参照

正規表現
http://docs.ruby-lang.org/ja/2.1.0/doc/spec=2fregexp.html

55
42
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
55
42

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?