概要
Javaで「MULTILINEフラグ(複数行モードを有効にする)」の動作を確認してみました。
以下のページを参考にしました。
実装
以下のファイルを作成しました。
JSample18_1.java
import java.util.regex.*;
class JSample18_1{
public static void main(String[] args){
String target1 = "apple is red\nlemon is yellow";
String target2 = "lemon is yellow\napple is red";
String regex = "^apple";
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.MULTILINE);
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 JSample18_1.java
$ java JSample18_1
apple is red
lemon is yellow:true
lemon is yellow
apple is red:false
---- ----
apple is red
lemon is yellow:true
lemon is yellow
apple is red:true
まとめ
何かの役に立てばと。