當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java Pattern asPredicate()用法及代碼示例


Pattern類的asPredicate()方法用於創建可用於匹配字符串的謂詞對象。謂詞是函數接口,因此可用作lambda表達式或方法引用的分配目標。

用法:

public Predicate asPredicate()

參數:此方法不接受任何參數。


返回值:此方法返回可用於匹配字符串的謂詞。

以下示例程序旨在說明toString()方法:

示例1:

// Java program to demonstrate 
// Pattern.splitAsStream(CharSequence input) method 
  
import java.util.regex.*; 
import java.util.function.*; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
        // create a REGEX String 
        String REGEX = "ee"; 
  
        // create the string 
        // in which you want to search 
        String actualString 
            = "aaeebbeecceeddee"; 
  
        // create a Pattern using REGEX 
        Pattern pattern 
            = Pattern.compile(REGEX); 
  
        // get Predicate Object 
        Predicate<String> predicate 
            = pattern.asPredicate(); 
  
        // check whether predicate match 
        // with actualString 
        boolean value = predicate 
                            .test(actualString); 
  
        // print result 
        System.out.println("value matched: "
                           + value); 
    } 
}
輸出:
value matched: true

示例2:

// Java program to demonstrate 
// Pattern.splitAsStream(CharSequence input) method 
  
import java.util.regex.*; 
import java.util.function.*; 
public class GFG { 
    public static void main(String[] args) 
    { 
        // create a REGEX String 
        String REGEX = "org"; 
  
        // create the string 
        // in which you want to search 
        String actualString 
            = "welcome geeks"; 
  
        // create a Pattern using REGEX 
        Pattern pattern 
            = Pattern.compile(REGEX); 
  
        // get Predicate Object 
        Predicate<String> predicate 
            = pattern.asPredicate(); 
  
        // check whether predicate match 
        // with actualString 
        boolean value 
            = predicate.test(actualString); 
  
        // print result 
        System.out.println("value matched: "
                           + value); 
    } 
}
輸出:
value matched: false

參考: https://docs.oracle.com/javase/10/docs/api/java/util/regex/Pattern.html#asPredicate()



相關用法


注:本文由純淨天空篩選整理自AmanSingh2210大神的英文原創作品 Pattern asPredicate() Method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。