📜  Java中的模式匹配(String,CharSequence)方法与示例

📅  最后修改于: 2022-05-13 01:55:36.020000             🧑  作者: Mango

Java中的模式匹配(String,CharSequence)方法与示例

Java中Pattern类的matches(String, CharSequence)方法用于回答正则表达式是否匹配输入。为此,我们编译给定的正则表达式并尝试将给定的输入与它匹配,其中正则表达式和输入都作为参数传递给方法。如果一个模式要被多次使用,编译一次并重用它会比每次调用这个方法更有效。

句法:

public static boolean matches(String regex, CharSequence input)

参数:此方法接受两个参数:

  • regex :此参数表示要编译的表达式。
  • input :要匹配的字符序列。

返回值:此方法返回一个布尔值,回答正则表达式是否匹配输入。

下面的程序说明了 match(String, CharSequence) 方法:

方案一:

// Java program to demonstrate
// Pattern.matches(String, CharSequence) method
  
import java.util.regex.*;
  
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
            = "geeksforgeeks";
  
        // use matches method to check the match
        boolean matcher = Pattern.matches(REGEX, actualString);
  
        // print values if match found
        if (matcher) {
            System.out.println("match found for Regex.");
        }
        else {
            System.out.println("No match found for Regex.");
        }
    }
}
输出:
match found for Regex.

方案二:

// Java program to demonstrate
// Pattern.matches(String, CharSequence) method
  
import java.util.regex.*;
  
public class GFG {
    public static void main(String[] args)
    {
        // create a REGEX String
        String REGEX = "(.*)(welcome)(.*)?";
  
        // create the string
        // in which you want to search
        String actualString
            = "The indian team wins worldcup";
  
        // use matches() method to check the match
        boolean matcher = Pattern.matches(REGEX, actualString);
  
        // print values if match found
        if (matcher) {
            System.out.println("match found for Regex.");
        }
        else {
            System.out.println("No match found for Regex.");
        }
    }
}
输出:
No match found for Regex.

参考:
https://docs.oracle.com/javase/10/docs/api/ Java/util/regex/Pattern.html#matches(java .lang.String, Java Java)