当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。