java - 如何使用 replaceAll 删除部分文本

标签 java replaceall

有一个字符串文本 System.out.println(text); 看起来像这样

So the traveller sat down by the side of that old man,
face to face with the serene sunset; 
and all his friends came softly back and stood around him. 

另一个String subText

System.out.println(subText); 只是上面字符串的一部分,看起来像这样

So the traveller sat down by the side of that old man,
face to face with the serene sunset;

我需要去掉这个 subText 部分 text = text.replaceAll(subtext, ""); 但这对文本没有任何作用吗?

最佳答案

在这种特殊情况下没关系,但您确实应该使用 replace 而不是 replaceAll:

text = text.replace(subtext, "");

replaceAll方法使用正则表达式,部分字符有特殊含义。

在这种特殊情况下,您不会看到任何差异,因为 subtext 中一定有细微的不同,因此在 text 中找不到。可能有多余的空格或换行符的编码不同。查看 System.out.println 生成的输出时,很难看出空白区域的差异。

关于java - 如何使用 replaceAll 删除部分文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19338355/

相关文章:

java - 在通过 fxml 设置的两个 JavaFX 窗口之间传递值?

java - 不幸的是,应用程序已停止,错误为零

具有排除模式的 Java 正则表达式 replaceAll

java - 如何删除字符串中问号(?)后面的尾随字符?

java - toString.replaceAll 在 Java 中如何工作?

java - 如何在每个管道前面插入反斜杠

java - 单元测试引发 : HsqlException user lacks privilege or object not found: ROWNUM

java - 当 Path 是接口(interface)时创建路径对象?

java - Netbeans java,在构建时打开一个cmd-window

java - 我知道如何从字符串中删除元音,但如何从字符串中删除某些空格