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

Javaで例を示したMatcher replaceAll()メソッド

このjava.util.regex.Matcherクラスのクラスは、さまざまなマッチング操作を行うエンジンを表します。このクラスにはコンストラクタがありませんが、使用できます。matches()java.util.regex.Patternクラスのメソッドで生成/このクラスのオブジェクトを取得します。

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("入力テキストを入力してください: ");
      String input = sc.nextLine();
      String regex = "[#%&*]";
      //パターンオブジェクトを生成します
      Pattern pattern = Pattern.compile(regex);
      //Matcherオブジェクトを生成します
      Matcher matcher = pattern.matcher(input);
      int count =0;
      while(matcher.find()) {
         count++;
      }
      //検索に使用されるパターン
      System.out.println("The are "+count+" 特殊文字 [# % & *] を指定されたテキストで置き換えました"
      //すべての特殊文字 [# % & *] で! String result = matcher.replaceAll("!");
      System.out.println("すべての特殊文字 [# % & *] で!: \n"+result);
   }
}

出力結果

入力テキストを入力してください:
ハロー# どーよ# お元気です *& welcome to T#utorials%point
The are 7 特殊文字 [# % & *] を指定されたテキストで置き換えました
すべての特殊文字 [# % & *] で!:
ハロー! どーよ! お元気ですか!! 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[]) {
      //ユーザーから文字列を読み取ります
      System.out.println("Enter a String");
      Scanner sc = new Scanner(System.in);
      String input = sc.nextLine();
      //正規表現はスペース(1つ以上)をマッチングします
      String regex = "\\s+";
      //正規表現をコンパイルします
      Pattern pattern = Pattern.compile(regex);
      //マッチングオブジェクトを検索します
      Matcher matcher = pattern.matcher(input);
      //すべてのスペース文字を単一のスペースに置き換えます
      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