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