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