JavaのMatcherreplaceAll()メソッドと例
java.util.regex.Matcher classは、さまざまな一致操作を実行するエンジンを表します。このクラスのコンストラクターはありません。クラスjava.util.regex.Patternのmatches()メソッドを使用して、このクラスのオブジェクトを作成/取得できます。
この(Matcher)クラスのreplaceAll()メソッドは、文字列値を受け入れ、入力内の一致したすべてのサブシーケンスを指定された文字列値に置き換えて、結果を返します。
例1
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ReplaceAllExample {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter input text: ");
String input = sc.nextLine();
String regex = "[#%&*]";
//Creating a pattern object
Pattern pattern = Pattern.compile(regex);
//Creating a Matcher object
Matcher matcher = pattern.matcher(input);
int count =0;
while(matcher.find()) {
count++;
}
//Retrieving Pattern used
System.out.println("The are "+count+" special characters [# % & *] in the given text");
//Replacing all special characters [# % & *] with ! String result = matcher.replaceAll("!");
System.out.println("Replaced all special characters [# % & *] with !: \n"+result);
}
} 出力
Enter input text: Hello# How # are# you *& welcome to T#utorials%point The are 7 special characters [# % & *] in the given text Replaced all special characters [# % & *] with !: Hello! How ! are! you !! welcome to T!utorials!point
例2
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ReplaceAllExample {
public static void main(String args[]) {
//Reading String from user
System.out.println("Enter a String");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
//Regular expression to match spaces (one or more)
String regex = "\\s+";
//Compiling the regular expression
Pattern pattern = Pattern.compile(regex);
//Retrieving the matcher object
Matcher matcher = pattern.matcher(input);
//Replacing all space characters with single space
String result = matcher.replaceAll(" ");
System.out.print("Text after removing unwanted spaces: \n"+result);
}
} 出力
Enter a String hello this is a sample text with irregular spaces Text after removing unwanted spaces: hello this is a sample text with irregular spaces
-
例を使用した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