Java Pattern matches(String ,CharSequence)方法及示例

来源:这里教程网 时间:2026-02-17 21:05:10 作者:

Java Pattern matches(String ,CharSequence)方法及示例

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

语法

public static boolean matches(String regex, CharSequence input)

参数: 该方法接受两个参数。

regex : 这个参数代表要编译的表达式。input :要匹配的字符序列。

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

下面的程序说明了 matches(String, CharSequence) 方法。

程序 1 :

// 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.

程序2

// 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.lang.CharSequence)

相关推荐