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 送给学长毕业祝福语简短