例を使用したJavaのマッチャーgroupCount()メソッド
java.util.regex.Matcherクラスは、さまざまな一致操作を実行するエンジンを表します。このクラスのコンストラクターはありません。クラスjava.util.regex.Patternのmatches()メソッドを使用して、このクラスのオブジェクトを作成/取得できます。
groupCount() この(Matcher)クラスのメソッドは、現在の一致のキャプチャグループの数を計算します。
例1
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("First group match: "+matcher.group(1));
System.out.println("Second group match: "+matcher.group(2));
System.out.println("Third group match: "+matcher.group(3));
System.out.println("Number of groups capturing: "+matcher.groupCount());
}
}
} 出力
First group match: This is a sample Text, 123 Second group match: 4 Third group match: , with numbers in between. Number of groups: 3
例2
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String[] args) {
String str1 = "<p>This <b>is</b> an <b>example</b>HTML <b>script</b> where <b>ever</b> alternative <b>word</b> is <b>bold</b></p>.";
//Regular expression to match contents of the bold tags
String regex = "(t(\\S+)t)(\\s)";
String str = "the words tit tat tweet tostff tact that tilt text start and end wit the letter t ";
//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(0));
}
System.out.println("Total capturing groups: "+matcher.groupCount());
}
} 出力
tit tat tweet tact that tilt text tart Total capturing groups: 3
-
例を使用したJavaのMatchermatches()メソッド
java.util.regex.Matcherクラスは、さまざまな一致操作を実行するエンジンを表します。このクラスのコンストラクタはありません。クラスjava.util.regex.Patternのmatches()メソッドを使用して、このクラスのオブジェクトを作成/取得できます。 matchs() このクラスのメソッドは、正規表現で表されるパターンと文字列を照合します(両方ともこのオブジェクトの作成中に指定されます)。一致する場合、このメソッドはtrueを返し、そうでない場合はfalseを返します。この方法の結果が真であるためには、領域全体が一致している必要があります。 例 import
-
例を使用したJavaのマッチャーstart()メソッド
java.util.regex.Matcherクラスは、さまざまな一致操作を実行するエンジンを表します。このクラスのコンストラクタはありません。クラスjava.util.regex.Patternのmatches()メソッドを使用して、このクラスのオブジェクトを作成/取得できます。 start() Matcherクラスのメソッドは、一致した文字の開始インデックスを返します。 例 部分式[...]は、入力文字列の中括弧内に指定された文字と一致します。次の例では、これを使用して文字tと一致します。ここで compile()メソッドを使用して正規表現をコンパイルしました。 Ma