简体   繁体   English

如何使用replaceAll删除部分文本

[英]How to remove a part of text using replaceAll

There is a String text System.out.println(text); 有一个String text System.out.println(text); looks like this 看起来像这样

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. 

Another String subText 另一个String subText

System.out.println(subText); is simply a part of the above string and looks like this 只是上面字符串的一部分,看起来像这样

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

I need to get rid of this subText part text = text.replaceAll(subtext, ""); 我需要摆脱这个subText部分text = text.replaceAll(subtext, ""); but this does not do anything with the text? 但这对文本没有任何作用?

In this particular case it does not matter, but you really should use replace instead of replaceAll : 在这种特殊情况下,这并不重要,但是您确实应该使用replace代替replaceAll

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

The replaceAll method uses regular expressions, and some characters have special meaning. replaceAll方法使用正则表达式,并且某些字符具有特殊含义。

In this particular case you won't see any difference because there must be something subtly different in subtext , so it cannot be found in text . 在这种特殊情况下,你将不会看到任何区别,因为必须有东西在微妙的不同subtext ,所以它不能找到text Perhaps there's extra white space or the line break character is encoded differently. 也许还有多余的空白,或者换行符的编码方式有所不同。 It's very hard to see differences in white space looking at output produced by System.out.println . System.out.println产生的输出来看,很难看到空白区域的差异。

The reason it's not working is because 'replaceAll()` expects the search term to be a regular expression . 它不起作用的原因是因为'replaceAll()`期望搜索项为正则表达式

You should use replace() , which use searches for plain text and incidentally still replaces all occurrences, instead: 您应该使用replace() ,该搜索使用纯文本搜索,并且顺便仍然替换所有出现的内容,而是:

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

As to why it didn't work with replaceAll() , who knows. 至于为什么它不能与replaceAll() ,谁知道呢。 To diagnose, you could see if in fact it's in your text as follows: 为了进行诊断,您可以查看实际上是否在文本中,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM