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.