Java如何替換所有指定(出現)的字串?

在Java編程中,如何替換所有指定(出現)的字串?

以下示例演示如何使用Matcher類的replaceAll()方法替換字串中的所有出現的子字串。

package com.zaixian;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ReplaceAllOccurrences {
    public static void main(String args[]) {
        Pattern p = Pattern.compile("Java");
        String instring = "Java and Javascript all is the best languages.";
        System.out.println("initial String: " + instring);
        Matcher m = p.matcher(instring);
        String tmp = m.replaceAll("Python");
        System.out.println("String after replacing 1st Match: " + tmp);
    }
}

上述代碼示例將產生以下結果 -

initial String: Java and Javascript all is the best languages.
String after replacing 1st Match: Python and Pythonscript all is the best languages.

上一篇: Java正則運算式 下一篇: Java PDF Box程式示例