Java 中的 Matcher group() 方法及示例

java.util.regex.Matcher 类表示执行各种匹配操作的引擎。此类没有构造函数,您可以使用 java.util.regex.Pattern 类的 matches() 方法创建/获取此类的对象。

这个 (Matcher) 类的group()方法在最后一次匹配期间返回匹配的输入子序列。

示例 1

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class GroupExample {
   public static void main(String[] args) {
      String str = "<p>This <b>is</b> an <b>example</b> HTML <b>script</b> "
         + "where <b>every</b> alternative <b>word</b> is <b>bold</b>. "
         + "It <i>also</i> contains <i>italic</i> words</p>";
      //Regular expression to match contents of the bold tags
      String regex = "<b>(\\S+)</b>|<i>(\\S+)</i>";
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Matching the compiled pattern in the String
      Matcher matcher = pattern.matcher(str);
      while (matcher.find()) {
         System.out.println(matcher.group());
      }
   }
}

输出

<b>is</b>
<b>example</b>
<b>script</b>
<b>every</b>
<b>word</b>
<b>bold</b>
<i>also</i>
<i>italic</i>

此方法的另一个变体接受表示组的整数变量,其中捕获的组从 1(从左到右)开始索引。

示例 2

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class GroupTest {
   public static void main(String[] args) {
      String regex = "(.*)(\\d+)(.*)";
      String input = "This is a sample Text, 1234, with numbers in between.";
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Matching the compiled pattern in the String
      Matcher matcher = pattern.matcher(input);
      if(matcher.find()) {
         System.out.println("match: "+matcher.group(0));
         System.out.println("First group match: "+matcher.group(1));
         System.out.println("Second group match: "+matcher.group(2));
         System.out.println("Third group match: "+matcher.group(3));
      }
   }
}

输出

match: This is a sample Text, 1234, with numbers in between.
First group match: This is a sample Text, 123
Second group match: 4
Third group match: , with numbers in between.
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值