Here's an example of replaceAll and replaceFirst usage:
String s = "Hi there! John here!";
s = s.replaceAll("ere", "arrr");
System.out.println(s);
// prints "Hi tharrr! John harrr!"
s = s.replaceFirst("!", "?");
System.out.println(s);
// prints "Hi tharrr? John harrr!"
As others have mentioned, both are actually regex-based:
System.out.println("Hello???".replaceAll("?", "!"));
// throws PatternSyntaxException: Dangling meta character '?'
The problem here is that ? is a regex metacharacter, and to treat it as a literal question mark, you have to escape it:
System.out.println("Hello???".replaceAll("\\?", "!"));
// prints "Hello!!!"
Sometimes the string the pattern is an unknown, in which case you can use Pattern.quote:
String unknown = "?";
System.out.println(
"Hello???".replaceAll(Pattern.quote(unknown), "!")
); // prints "Hello!!!"
To complicate matters slightly, the replacement string is actually also regex-based.
System.out.println(
"USD 10".replaceAll("USD", "dollar$")
);
// throws StringIndexOutOfBoundsException: index out of range: 7
To quote a replacement string, you use Matcher.quoteReplacement:
System.out.println(
"USD 10".replaceAll("USD", Matcher.quoteReplacement("dollar$"))
); // prints "dollar$ 10"
But what if I just want to do a simple no-regex replacement?
Then, to use replaceFirst, you have to quote both the pattern and the replacement strings:
import java.util.regex.Pattern;
import java.util.regex.Matcher;
String replaceFrom = ...;
String replaceTo = ...;
String before = ...;
String after = before.replaceFirst(
Pattern.quote(replaceFrom), Matcher.quoteReplacement(replaceTo)
);
And if you need a replaceAll, then you just use the usual non-regex replace method instead:
String after = before.replace(replaceFrom, replaceTo);
originalString.replaceAll(moreTag, newContent), and how are you checking for success?