2013-10-12 32 views
1

有一个String text System.out.println(text);看起来像这样如何使用的replaceAll

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, "");但这不对文本做任何事情?

+3

当心:String.replaceAll在Java中使用正则表达式。 – luiscubal

+2

它适合我。 (请确保你在子文本中有确切的东西。) –

+0

可能在删除它之前检查子文本是否在字符串中。可能是您的潜台词中的错字。 if(text.contains(subtext)){do stuff} else {print error} – sirFunkenstine

回答

6

在这种特殊情况下也不要紧,但你真的应该使用replace而不是replaceAll

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

replaceAll方法使用正则表达式,以及一些字符具有特殊的意义。

在这种特殊情况下,您不会看到任何差异,因为在subtext中必定存在微妙差异,因此无法在text中找到。也许有额外的空白或换行符的编码方式不同。看到System.out.println产生的输出的空白是很难看到的。

2

它不工作的原因是因为'replaceAll()'期望搜索词是正则表达式

您应该使用replace(),其中使用搜索纯文本以及偶然还是替换所有出现的,而不是:

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

至于为什么没有与replaceAll()工作,谁知道。为了诊断,你可以看到,如果实际上它是在你的文字如下:

System.out.println(text.contains(subtext)); 
+0

不是多行只影响'^'和'$'的行为? – Joni

+0

@joni是的。当时看起来似乎合情合理,但我已经收回了这个,并且放入了一些有用的东西 – Bohemian