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
相關用法
- Java Pattern pattern()用法及代碼示例
- Java Pattern toString()用法及代碼示例
- Java Pattern splitAsStream()用法及代碼示例
- Java Pattern asPredicate()用法及代碼示例
- Java Matcher pattern()用法及代碼示例
- Java Pattern flags()用法及代碼示例
- Java Pattern compile(String)用法及代碼示例
- Java Pattern compile(String,int)用法及代碼示例
- Java Pattern quote(String)用法及代碼示例
- Java Pattern split(CharSequence)用法及代碼示例
- Java Matcher usePattern(Pattern)用法及代碼示例
- Java Pattern split(CharSequence,int)用法及代碼示例
- Java Pattern matches(String ,CharSequence)用法及代碼示例
- Java Java lang.Long.highestOneBit()用法及代碼示例
- Java Java lang.Long.lowestOneBit()用法及代碼示例
注:本文由純淨天空篩選整理自AmanSingh2210大神的英文原創作品 Pattern matcher(CharSequence) method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。