📜  Java中的模式匹配器(CharSequence)方法与示例

📅  最后修改于: 2022-05-13 01:54:33.986000             🧑  作者: Mango

Java中的模式匹配器(CharSequence)方法与示例

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

句法:

public Matcher matcher(CharSequence input)

参数:此方法接受单个参数输入,该参数表示要匹配的字符序列。

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

下面的程序说明了 matcher(CharSequence) 方法:

方案一:

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

方案二:

// 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 Java Java)