60
54

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.

Javaで改行コードを検出するために使える正規表現 "\r\n|[\n\r\u2028\u2029\u0085]"

Last updated at Posted at 2013-07-23

よく知られているように,テキストを改行する際の文字コードは環境に依存する.Windowsでは\r\n, Linuxでは\nとか.

汎用的に改行コードを検知するにはどうしたらいいかと思ってOpenJDKのソースコードを見てみると
Scannerクラスでは以下のような正規表現が使われていたのでメモしておく.

Scanner.java(500行目付近)
String LINE_SEPARATOR_PATTERN =  "\r\n|[\n\r\u2028\u2029\u0085]";

ちなみに,u2028はLine Separator,u2029はPragraph Separator,u0085はNext Line らしい


なお,BuffredReaderクラスではもうちょっと泥臭い読み方をしている模様

BufferedReader#read()(180行目あたり)
if (skipLF) {
    skipLF = false;
    if (cb[nextChar] == '\n') {
        nextChar++;
        continue;
    }
}
BufferedReader#readline()(350行目あたり)
if (c == '\r') {
    skipLF = true;
}
60
54
0

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
60
54

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?