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


Java Pattern matcher(CharSequence)用法及代碼示例


Pattern類的matcher(CharSequence)方法用於生成匹配器,該匹配器將有助於將給定輸入作為參數匹配此模式的方法。當我們需要一次根據文本檢查一個模式,並且Pattern類的默認設置合適時,Pattern.matches()方法非常有用。

用法:

public Matcher matcher(CharSequence input)

參數:此方法接受單個參數輸入,該參數表示要匹配的字符序列。


返回值:此方法為此模式返回一個新的匹配器。

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

示例1:

// Java program to demonstrate 
// Pattern.matcher(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"; 
  
        // create a Pattern 
        Pattern pattern = Pattern.compile(REGEX); 
  
        // get a matcher object 
        Matcher matcher = pattern.matcher(actualString); 
  
        // print values if match found 
        boolean matchfound = false; 
        while (matcher.find()) { 
            System.out.println("found the Regex in text:"
                               + matcher.group() 
                               + " starting index:" + matcher.start() 
                               + " and ending index:"
                               + matcher.end()); 
  
            matchfound = true; 
        } 
        if (!matchfound) { 
            System.out.println("No match found for Regex."); 
        } 
    } 
}
輸出:
found the Regex in text:geeksforgeeks starting index:0 and ending index:13

示例2:

// Java program to demonstrate 
// Pattern.matcher(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 
            = "geeksforgeeks"; 
  
        // create a Pattern 
        Pattern pattern = Pattern.compile(REGEX); 
  
        // get a matcher object 
        Matcher matcher = pattern.matcher(actualString); 
  
        // print values if match found 
        boolean matchfound = false; 
        while (matcher.find()) { 
            System.out.println("match found"); 
            matchfound = true; 
        } 
        if (!matchfound) { 
            System.out.println("No match found"); 
        } 
    } 
}
輸出:
No match found

參考文獻:
https://docs.oracle.com/javase/10/docs/api/java/util/regex/Pattern.html#matcher(java.lang.CharSequence)



相關用法


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