Java如何替换所有指定(出现)的字符串?

Posted borter

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java如何替换所有指定(出现)的字符串?相关的知识,希望对你有一定的参考价值。

在Java编程中,如何替换所有指定(出现)的字符串?

以下示例演示如何使用Matcher类的replaceAll()方法替换字符串中的所有出现的子字符串。

package com.yiibai;

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);
    }
}
Java

上述代码示例将产生以下结果 -

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

 

以上是关于Java如何替换所有指定(出现)的字符串?的主要内容,如果未能解决你的问题,请参考以下文章