Java 中的 Pattern asPredicate() 方法以及示例


java.util.function 包的 Predicate 介面可作為 lambda 表示式的目標。此介面的 test 方法接受一個值,並用當前的 Predicate 物件值驗證該值。此方法在匹配時返回 true,否則返回 false。

java.util.regex.Pattern 類的 asPredicate() 方法返回一個 Predicate 物件,它可以使用表示正則表示式的當前 Pattern 物件已編譯的字串來匹配字串。

示例 1

import java.util.Scanner;
import java.util.function.Predicate;
import java.util.regex.Pattern;
public class AsPredicateExample {
   public static void main( String args[] ) {
      //Reading string value
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter input string");
      String input = sc.nextLine();
      //Regular expression to find digits
      String regex = "[t]";
      //Compiling the regular expression
      Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
      //Converting the regular expression to predicate
      Predicate<String> predicate = pattern.asPredicate();
      //Testing the predicate with the input string
      boolean result = predicate.test(input);
      if(result) {
         System.out.println("Match found");
      } else {
         System.out.print("Match not found");
      }
   }
}

輸出

Enter input string
Tutorialspoint
Number of matches: 3

示例 2

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
import java.util.function.Predicate;
import java.util.regex.Pattern;
public class AsPredicateExample {
   public static void main( String args[] ) {
      ArrayList<String> list = new ArrayList<String>();
      list.addAll(Arrays.asList("Java", "JavaFX", "Hbase", "JavaScript"));
      //Regular expression to find digits
      String regex = "[J]";
      //Compiling the regular expression
      Pattern pattern = Pattern.compile(regex);
      //Converting the regular expression to predicate
      Predicate<String> predicate = pattern.asPredicate();
      list.forEach(n -> { if (predicate.test(n)) System.out.println("Match found "+n); });
   }
}

輸出

Match found Java
Match found JavaFX
Match found JavaScript

更新於: 2019 年 11 月 20 日

246 次瀏覽

開啟你的 職業生涯

透過完成課程完成認證

開始
廣告
© . All rights reserved.