問題一覧に戻る
中級高度な機能
問題93: 正規表現基礎

Javaの正規表現は強力なテキストパターンマッチングのためにPatternとMatcherクラスを使用します。Pattern.compile()は効率のために正規表現パターンをコンパイルし、matcher()はマッチを見つけるためのMatcherオブジェクトを作成します。find()メソッドは次のマッチを見つけ、group()はマッチしたテキストを取得します。これにより複雑なテキスト解析と検証タスクが可能になります。

import java.util.regex.*;

public class Main {
public static void main(String[] args) {
String text = "Call 123-4567 or 987-6543";

// パターンをコンパイル
Pattern pattern = Pattern.("\\d{3}-\\d{4}");
// マッチャーを作成
matcher = pattern.__(text);

while (matcher.()) {
System.out.println("Found: " + matcher.());
}
}
}