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

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

java.util.regex.Matcher类表示执行各种匹配操作的引擎。此类没有构造函数,可以使用类java.util.regex.Pattern的matchs()方法创建/获取此类的对象。

锚定边界用于匹配区域匹配,例如^和$。默认情况下,匹配器使用锚定范围,您可以使用useAnchoringBounds()方法从使用锚定范围切换到非锚定范围。

此(Matcher)类的hasAnchoringBounds()方法验证当前匹配器是否使用锚定边界(如果是),否则返回true,否则返回false。

例1

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class HasAnchoringBoundsExample {
   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";
      //パターンオブジェクトの作成
      Pattern pattern = Pattern.compile(regex);
      //マッチャーオブジェクトの作成
      Matcher matcher = pattern.matcher(input);
      //アンクリングバウンズの確認
      boolean bool = matcher.hasAnchoringBounds();
      //マッチングの確認
      if(bool) {
         System.out.println("Current matcher uses anchoring bounds");
      } else {
         System.out.println("Current matcher uses non-anchoring bounds);
      }
      if(matcher.matches()) {
         System.out.println("マッチングが見つかりました");
      } else {
         System.out.println("マッチングが見つかりませんでした");
      }
   }
}

出力結果

現在のマッチャーはアンクリングバウンズを使用しています
マッチングが見つかりませんでした

例2

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Trail {
   public static void main( String args[] ) {
      //文字列値の読み取り
      Scanner sc = new Scanner(System.in);
      System.out.println("入力文字列を入力してください");
      String input = sc.nextLine();
      //数字を見つけるための正規表現
      String regex = ".";*\\d+.*";"
      //正規表現のコンパイル
      Pattern pattern = Pattern.compile(regex);
      //正規表現の印刷
      System.out.println("構文化された正規表現: " );+pattern.toString());
      //matcherオブジェクトの取得
      Matcher matcher = pattern.matcher(input);
      matcher.useAnchoringBounds(false);
      boolean hasBounds = matcher.hasAnchoringBounds();
      if(hasBounds) {
         System.out.println("Current matcher uses anchoring bounds");
      } else {
         System.out.println("Current matcher uses non-anchoring bounds);
      }
      //verifying whether match occurred
      if(matcher.matches()) {
         System.out.println("Given String contains digits");
      } else {
         System.out.println("Given String does not contain digits");
      }
   }
}

出力結果

Enter input string
hello sample 2
Compiled regular expression: .*\d+.*
Current matcher uses non-anchoring bounds
Given String contains digits