English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

مثال على طريقة group() في Matcher في Java

The java.util.regex.Matcher class represents an engine for performing various matching operations. This class has no constructor, and can be usedmatches()The method of the java.util.regex.Pattern class creates/gets an object of this class.

This (Matcher) classgroup()The method returns the matched input subsequence during the last match.

例子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 the content of bold tags
      String regex = "<b>(\\S+)</b>|<i>(\\S+)</i>";
      //create a pattern object
      Pattern pattern = Pattern.compile(regex);
      // تطابق النمط المسبق
      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>

Another variant of this method accepts an integer variable representing the group, where the captured groups are indexed starting from 1 (from left to right).

例子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.";
      //create a pattern object
      Pattern pattern = Pattern.compile(regex);
      // تطابق النمط المسبق
      Matcher matcher = pattern.matcher(input);
      if(matcher.find()) {
         System.out.println("التطابق: " + matcher.group(0));
         System.out.println("المجموعة الأولى من التطابق: " + matcher.group(1));
         System.out.println("المجموعة الثانية من التطابق: " + matcher.group(2));
         System.out.println("المجموعة الثالثة من التطابق: " + matcher.group(3));
      }
   }
}

نتيجة الإخراج

التطابق: This is a sample Text, 1234, مع الأرقام بينها.
المجموعة الأولى من التطابق: This is a sample Text, 123
المجموعة الثانية من التطابق: 4
المجموعة الثالثة من التطابق: ,رقم بينها.
من المحتمل أن تفضلها