0
0

Javaで「UNIX_LINESフラグ(\nのみ行末記号として認識される)」の動作を確認してみた

Posted at

概要

Javaで「UNIX_LINESフラグ(\nのみ行末記号として認識される)」の動作を確認してみました。
以下のページを参考にしました。

実装

以下のファイルを作成しました。

JSample20_1.java
import java.util.regex.*;

class JSample20_1{
  public static void main(String[] args){
    String target1 = "Thank You!\r\nGood Bye";
    String target2 = "Good Bye\nThank You!";
    String target3 = "Good Bye\r\nThank You!";

    String regex = "Bye$";
    Pattern p1 = Pattern.compile(regex, Pattern.MULTILINE);

    Matcher m1_1 = p1.matcher(target1);
    System.out.println(target1 + ":" + m1_1.find());
    Matcher m1_2 = p1.matcher(target2);
    System.out.println(target2 + ":" + m1_2.find());
    Matcher m1_3 = p1.matcher(target3);
    System.out.println(target3 + ":" + m1_3.find());

    System.out.println("---- ----");

    Pattern p2 = Pattern.compile(regex, Pattern.MULTILINE|Pattern.UNIX_LINES);

    Matcher m2_1 = p2.matcher(target1);
    System.out.println(target1 + ":" + m2_1.find());
    Matcher m2_2 = p2.matcher(target2);
    System.out.println(target2 + ":" + m2_2.find());
    Matcher m2_3 = p2.matcher(target3);
    System.out.println(target3 + ":" + m2_3.find());
  }
}

以下のコマンドを実行しました。

$ javac JSample20_1.java 
$ java JSample20_1 
Thank You!
Good Bye:true
Good Bye
Thank You!:true
Good Bye
Thank You!:true
---- ----
Thank You!
Good Bye:true
Good Bye
Thank You!:true
Good Bye
Thank You!:false

まとめ

何かの役に立てばと。

0
0
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
0
0