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());
}

更新於: 2019 年 7 月 30 日

573 次瀏覽

啟動你的 職業生涯

完成課程並獲得認證

開始學習
廣告
© . All rights reserved.