Java 如何使用replaceAll删除部分文本
有一个Java 如何使用replaceAll删除部分文本,java,replaceall,Java,Replaceall,有一个字符串文本 System.out.println(文本)看起来像这样 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. So the traveller sat down by the side of that old man, fac
字符串文本
System.out.println(文本)代码>看起来像这样
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.
So the traveller sat down by the side of that old man,
face to face with the serene sunset;
另一个字符串子文本
System.out.println(子文本)
只是上述字符串的一部分,如下所示
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.
So the traveller sat down by the side of that old man,
face to face with the serene sunset;
我需要去掉这个subText
parttext=text.replaceAll(subText,”)
但这对文本没有任何作用?在这种情况下,这并不重要,但您确实应该使用replace
而不是replaceAll
:
text = text.replace(subtext, "");
replaceAll
方法使用正则表达式,有些字符具有特殊含义
在这种特殊情况下,您将看不到任何差异,因为在子文本
中必须存在一些微妙的差异,因此在文本
中找不到它。可能有额外的空白,或者换行符的编码不同。在查看由System.out.println生成的输出时,很难看到空格中的差异。在这种特殊情况下,这并不重要,但您确实应该使用replace
而不是replaceAll
:
text = text.replace(subtext, "");
replaceAll
方法使用正则表达式,有些字符具有特殊含义
在这种特殊情况下,您将看不到任何差异,因为在子文本
中必须存在一些微妙的差异,因此在文本
中找不到它。可能有额外的空白,或者换行符的编码不同。在查看由System.out.println产生的输出时,很难看到空格中的差异。它不起作用的原因是因为'replaceAll()'期望搜索项是正则表达式
您应该使用replace()
,它使用纯文本搜索,顺便说一句,仍然替换所有出现的内容,而不是:
text = text.replace(subtext, "");
至于为什么它不能与replaceAll()
一起使用,谁知道呢。要进行诊断,您可以查看文本中是否存在以下内容:
System.out.println(text.contains(subtext));
它不起作用的原因是“replaceAll()”期望搜索项是正则表达式
您应该使用replace()
,它使用纯文本搜索,顺便说一句,仍然替换所有出现的内容,而不是:
text = text.replace(subtext, "");
至于为什么它不能与replaceAll()
一起使用,谁知道呢。要进行诊断,您可以查看文本中是否存在以下内容:
System.out.println(text.contains(subtext));
注意:Java中的String.replaceAll使用正则表达式。它适合我。(确保您在子文本中有确切的内容。)在删除它之前,可能会检查该子文本是否在字符串中。可能是你的潜台词有误。如果(text.contains(subtext)){do stuff}或者{print error}您的基本代码看起来不错。发布演示问题的SSCCE
。您也可以先删除一个较小的文本字符串,以确保代码正常工作,并且在任何地方都没有输入错误。然后用一个更大的字符串试试,因为除非你有一个完全匹配的字符串,否则任何东西都不会被替换。注意:Java中的string.replaceAll使用正则表达式。它对我很有用。(确保您在子文本中有确切的内容。)在删除它之前,可能会检查该子文本是否在字符串中。可能是你的潜台词有误。如果(text.contains(subtext)){do stuff}或者{print error}您的基本代码看起来不错。发布演示问题的SSCCE
。您也可以先删除一个较小的文本字符串,以确保代码正常工作,并且在任何地方都没有输入错误。然后用一个更大的字符串试试,因为除非你有一个精确的匹配,否则什么都不会被替换。多行不会只影响^
和$
的行为吗?@joni yeah。当时似乎有道理,但我收回了这一点,并加入了一些有用的东西,而不是说多行只影响^
和$
?@joni-yeah的行为。当时看起来似乎有道理,但我收回了这一点,转而加入了一些有用的东西