Java Pattern asPredicate()方法及示例

Java Pattern asPredicate()方法及示例

Pattern 类的 asPredicate () 方法用于创建一个predicate对象,该对象可用于匹配一个字符串。Predicate是一个功能接口,因此可以作为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()

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程