概要
Javaで「リージョン(対象文字列の中のパターンと比較する範囲)を設定する」の動作を確認してみました。
以下のページを参考にしました。
実装
以下のファイルを作成しました。
JSample26_1.java
import java.util.regex.*;
class JSample26_1{
public static void main(String[] args){
String target = "dancer singer";
String regex = "\\b.*?er";
Pattern p = Pattern.compile(regex);
Matcher m1 = p.matcher(target);
if (m1.find()){
System.out.println(m1.group());
}else{
System.out.println("not match");
}
Matcher m2 = p.matcher(target);
m2.region(7, 13);
if (m2.find()){
System.out.println(m2.group());
}else{
System.out.println("not match");
}
}
}
以下のコマンドを実行しました。
$ javac JSample26_1.java
$ java JSample26_1
dancer
singer
まとめ
何かの役に立てばと。