概要
Javaで「正規表現グループを設定してパターンの一部にマッチした文字列を取得する」の動作を確認してみました。
以下のページを参考にしました。
実装
以下のファイルを作成しました。
JSample13_1.java
import java.util.regex.*;
class JSample13_1{
public static void main(String[] args){
String regex = "(\\d{3})-(\\d{4})";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher("〒123-4567");
if (m.find()){
System.out.println(m.group()); // 123-4567
System.out.println(m.group(0)); // 123-4567
System.out.println(m.group(1)); // 123
System.out.println(m.group(2)); // 4567
}
}
}
以下のコマンドを実行しました。
$ javac JSample13_1.java
$ java JSample13_1
123-4567
123-4567
123
4567
まとめ
何かの役に立てばと。