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