概要
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
まとめ
何かの役に立てばと。