How to replace string only once without regex in Java?
As Laurence suggested, you can use Pattern.quote
like this:
newString = string.replaceFirst(Pattern.quote(substring),
Matcher.quoteReplacement(replacement));
quote
creates a regex that literally matches the substring, and quoteReplacement
creates a literal replacement string.
Another approach is simply to compile the substring as a literal regex like this:
newString = Pattern.compile(substring, Pattern.LITERAL).
matcher(string).replaceFirst(Matcher.quoteReplacement(replacement));
This might be slightly more efficient, but also a bit less clear.
You could also do it manually, since you're only wanting to replace the first occurrence. But regexes are pretty efficient, so don't optimise prematurely!
You should use already tested and well documented libraries in favor of writing your own code!
StringUtils.replaceOnce("aba", "a", "") = "ba"
The StringUtils
class is from Apache Commons Lang3 package and can be imported in Maven like this:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.8.1</version>
</dependency>