Java Pattern matcher(CharSequence)方法及示例

Java Pattern matcher(CharSequence)方法及示例

Pattern 类的 matcher(CharSequence) 方法用于生成一个匹配器,该匹配器将有助于将给定的输入作为参数与该模式的方法匹配。Pattern.matches()方法在我们需要对一个文本进行一次性的模式检查时非常有用,而且Pattern类的默认设置也很合适。

语法

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)。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程