English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

JavaのMatcher lookingAt()メソッドの例

java.util.regex.Matcherクラスは、さまざまなマッチング操作を実行するエンジンを表します。このクラスには構造関数がありませんが、java.util.regex.Patternクラスのmatches()メソッドを使用して作成できます。/このクラスのオブジェクトを取得します。

MatcherのクラスlookingAt()メソッドは、指定された入力テキストをパターンと一致させることを開始区域からチェックします。一致する場合、このメソッドはtrueを返します。不一致の場合、falseを返します。matches()メソッドとは異なり、このメソッドは区域全体が一致する必要はありません。

例子1

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
   public static void main(String[] args) {
      String regex = "(.*)(\\d+)(.*)";
      String input = "This is a sample Text, 1234, with numbers in between. "
         + "\n This is the second line in the text "
         + "\n This is third line in the text";
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Creating a Matcher object
      Matcher matcher = pattern.matcher(input);
      //checking for the match
      if(matcher.lookingAt()) {
         System.out.println("Match found");
      } else {
         System.out.println("Match not found");
      }
   }
}

出力結果

Match found

例子2

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class LookingAtExample {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter String1: ");
      String input1 = sc.nextLine();
      System.out.println("Enter String2: ");
      String input2 = sc.nextLine();
      System.out.println("Enter String3: ");
      String input3 = sc.nextLine();
      String input = input1+"\n"+input2+"\n"+input3;
      System.out.println(input);
      //数字を含む単語をマッチする正規表現
      String regex = ".*\\d+.*";
      //正規表現をコンパイル
      Pattern pattern = Pattern.compile(regex);
      //マッチャーオブジェクトを取得
      Matcher matcher = pattern.matcher(input);
      //マッチが発生したか確認
      boolean bool = matcher.lookingAt();
      if(bool) {
         System.out.println("入力に数字が含まれている");
      } else {
         System.out.println("入力に数字が含まれていません");
      }
   }
}

出力結果

文字列を入力1:
サンプルテキスト2
文字列を入力2:
データ
文字列を入力3:
サンプル
サンプルテキスト2
データ
サンプル
入力に数字が含まれている場合