Java中的MatchResult start()方法以及示例。
该java.util.regex.MatcheResult 接口提供方法来检索匹配的结果。
您可以使用Matcher类的toMatchResult()方法获取此接口的对象。此方法返回一个MatchResult对象,该对象表示当前匹配器的匹配状态。
此接口的start()方法返回当前匹配项的开始索引。
示例
import java.util.Scanner;
import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StartExample {
public static void main(String args[]) {
//从用户读取字符串
System.out.println("Enter a String");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
String regex = "\\W";
//编译正则表达式
Pattern pattern = Pattern.compile(regex);
//检索匹配器对象
Matcher matcher = pattern.matcher(input);
if(matcher.find()) {
System.out.println("Match occurred");
}else {
System.out.println("Match not occurred");
}
//检索MatchResult对象
MatchResult res = matcher.toMatchResult();
int start = res.start();
System.out.println(start);
}
}输出结果
Enter a String This * is # sample % text with & non word characters Match occurred 4
热门推荐
10 小红书平安祝福语简短
11 生日祝福语大全女孩简短
12 收生日红包祝福语 简短
13 领证幽默祝福语简短
14 法考面试祝福语简短
15 老哥出门祝福语简短语
16 送灯祝福语简短独特
17 幼儿狗年祝福语大全简短
18 好听的元旦简短祝福语