Java 正則表示式中 Matcher.group() 方法的作用
java.time.Matcher.group() 方法用於在輸入序列字串中查詢與所需模式匹配的子序列。此方法返回匹配上一匹配項(甚至可能是空字串)的子序列。
下面給出了演示 Java 正則表示式中 Matcher.group() 方法的程式
示例
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Demo {
public static void main(String args[]) {
Pattern p = Pattern.compile("\w\d");
Matcher m = p.matcher("This is gr8");
System.out.println("The input string is: This is gr8");
System.out.println("The Regex is: \w\d");
System.out.println();
if (m.find()) {
System.out.println("Match: " + m.group());
}
}
}輸出
The input string is: This is gr8 The Regex is: \w\d Match: r8
下面我們來理解一下上述程式。
在字串序列 "This is gr8" 中搜索子序列 “\w\d”。find() 方法用於查詢子序列是否在輸入序列中,並使用 group() 方法列印所需的輸出。下面一段程式碼演示了這一點
Pattern p = Pattern.compile("\w\d");
Matcher m = p.matcher("This is gr8");
System.out.println("The input string is: This is gr8");
System.out.println("The Regex is: \w\d");
System.out.println();
if (m.find()) {
System.out.println("Match: " + m.group());
}
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP