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


Java Pattern matches(String ,CharSequence)用法及代碼示例


Java中Pattern類的matchs(String,CharSequence)方法用於回答正則表達式在輸入上是否匹配。為此,我們編譯給定的正則表達式,並嘗試將給定的輸入與正則表達式進行匹配,其中正則表達式和輸入均作為參數傳遞給方法。如果要多次使用某個模式,則將其編譯一次並重新使用它將比每次調用此方法都更加有效。

用法:

public static boolean matches(String regex, CharSequence input)

參數:此方法接受兩個參數:


  • regex:此參數表示要編譯的表達式。
  • input:要匹配的字符序列。

返回值:此方法返回一個布爾值,回答正則表達式是否與輸入匹配。

以下示例程序旨在說明matchs(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)



相關用法


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