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[]) {
//Reading String from user
System.out.println("Enter a String");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
String regex = "\W";
//Compiling the regular expression
Pattern pattern = Pattern.compile(regex);
//Retrieving the matcher object
Matcher matcher = pattern.matcher(input);
if(matcher.find()) {
System.out.println("Match occurred");
}else {
System.out.println("Match not occurred");
}
//Retrieving the MatchResult object
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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP