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

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

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

この(Matcher)クラスのappendReplacement()メソッドはStringBufferオブジェクトとString(置き換え文字列)を引数に取り、置き換え文字列でマッチング内容を置き換え、入力データをStringBufferオブジェクトに追加します。

内部で、このメソッドは各文字を入力文字列から読み取り、Stringバッファに追加し、マッチが発生したときは、文字列のマッチング部分をバッファに追加する代わりに、文字列を置き換え、マッチング子文字列の次の位置から続けます。

例1

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class appendReplacementExample {
   public static void main(String[] args) {
      String str = "<p>This <b>is</b> an <b>example</b>HTML <b>script</b>.</p>";
      //Regular expression to match contents of the bold tags
      String regex = "<b>(\\S+)</b>";
      System.out.println("Input string: \n"+str);
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Matching the compiled pattern in the String
      Matcher matcher = pattern.matcher(str);
      //Creating an empty string buffer
      StringBuffer sb = new StringBuffer();
      while (matcher.find()) {
         matcher.appendReplacement(sb, "BoldData");
      }
      matcher.appendTail(sb);
      System.out.println("Contents of the StringBuffer: \n"+ sb.toString() );
   }
}

出力結果

Input string:
<p>This <b>is</b> an <b>example</b> HTML <b>script</b>.</p>
Contents of the StringBuffer:
This BoldData an BoldData HTML BoldData.
<p>This BoldData an BoldData HTML BoldData.</p>

例子2

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class appendReplacementExample {
   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;
      StringBuffer buffer = new StringBuffer();
      System.out.println("Removing the special character form the given string");
      while(matcher.find()) {
         count++;
         matcher.appendReplacement(buffer, "");
      }
      matcher.appendTail(buffer);
      //使用されたパターンを取得
      System.out.println("特別な文字が発生しました"+count+"指定されたテキスト中の出現回数"
      System.out.println("すべてのテキストを削除した後のテキスト \n"+buffer.toString());
   }
}

出力結果

入力テキストを入力してください:
Hello# how$ are& yo|u welco<me to> Tut-oria@ls@po-in#t.
指定された文字列から特別な文字を削除
特別な文字が発生しました 11 指定されたテキスト中の出現回数
すべてのテキストを削除した後のテキスト
Hello how are you welcome to w3codebox.