Java 中的 MatchResult group() 方法示例。
java.util.regex.MatcheResult 介面提供了獲取匹配結果的方法。
你可以使用 **Matcher** 類的 **toMatchResult()** 方法獲取這個介面的物件。這個方法返回一個 MatchResult 物件,它表示當前匹配器的匹配狀態。
這個介面的 **group()** 方法返回一個字串值,表示在上一次匹配中給定輸入序列中匹配的子串。
示例
import java.util.Scanner;
import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class GroupExample {
public static void main( String args[] ) {
String regex = "(.*)(\d+)(.*)";
//Reading input from user
Scanner sc = new Scanner(System.in);
System.out.println("Enter input text: ");
String input = sc.nextLine();
//Instantiating the Pattern class
Pattern pattern = Pattern.compile(regex);
//Instantiating the Matcher class
Matcher matcher = pattern.matcher(input);
//verifying whether a match occurred
if(matcher.find()) {
System.out.println("Match found");
}
MatchResult res = matcher.toMatchResult();
String matchedData = res.group();
System.out.println(matchedData);
}
}輸出
Enter input text: This is a sample Text, 123 Match found This is a sample Text, 123
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP