سؤال

There is a 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

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, ""); 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:

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

The replaceAll method uses regular expressions, and some characters have special meaning.

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. 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.

نصائح أخرى

The reason it's not working is because 'replaceAll()` expects the search term to be a regular expression.

You should use replace(), which use searches for plain text and incidentally still replaces all occurrences, instead:

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

As to why it didn't work with replaceAll(), who knows. To diagnose, you could see if in fact it's in your text as follows:

System.out.println(text.contains(subtext));
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top