String类的replaceAll()方法接受两个字符串,一个代表正则表达式以查找字符串,另一个代表替换字符串。
并且,用给定的String替换所有匹配的序列。因此,用String中的另一个单词替换特定单词-
获取所需的字符串。
通过传递对表示要替换的单词的正则表达式(在单词边界“ \ b”内)和替换字符串作为参数,对获得的字符串调用全部替换方法。
检索结果并打印。
import java.io.File; import java.io.IOException; import java.util.Scanner; public class ReplacingWords { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(new File("D://sample.txt")); String input; StringBuffer sb = new StringBuffer(); while (sc.hasNextLine()) { input = sc.nextLine(); sb.append("\n"+input); } String contents = sb.toString(); System.out.println("Contents of the string: "+contents); contents = contents.replaceAll("\\b(cainiaojc.com)\\b", "TP"); System.out.println("Contents of the string after replacement: "); System.out.println(contents); } }
输出结果
Contents of the string: (cainiaojc.com) originated from the idea that there exists a class of readers who respond better to on-line content and prefer to learn new skills at their own pace from the comforts of their drawing rooms. At (cainiaojc.com) we provide high quality learning-aids for free of cost. (cainiaojc.com) recently developed an app to help students from 6th to 12th. Contents of the string after replacement: TP originated from the idea that there exists a class of readers who respond better to on-line content and prefer to learn new skills at their own pace from the comforts of their drawing rooms. At TP we provide high quality learning-aids for free of cost. TP recently developed an app to help students from 6th to 12th.