0
0

Javaで「DOTALLフラグ(ドット(.)が行末記号とマッチする)」の動作を確認してみた

Posted at

概要

Javaで「DOTALLフラグ(ドット(.)が行末記号とマッチする)」の動作を確認してみました。
以下のページを参考にしました。

実装

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

JSample19_1.java
import java.util.regex.*;

class JSample19_1{
  public static void main(String[] args){
    String target1 = "<p>Lemon is yellow.Strawberry is red</p>";
    String target2 = "<p>Lemon is yellow.\nStrawberry is red</p>";

    String regex = "<p>.*</p>";
    Pattern p1 = Pattern.compile(regex);

    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());

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

    Pattern p2 = Pattern.compile(regex, Pattern.DOTALL);

    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());
  }
}

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

$ javac JSample19_1.java 
$ java JSample19_1 
<p>Lemon is yellow.Strawberry is red</p>:true
<p>Lemon is yellow.
Strawberry is red</p>:false
---- ----
<p>Lemon is yellow.Strawberry is red</p>:true
<p>Lemon is yellow.
Strawberry is red</p>:true

まとめ

何かの役に立てばと。

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