How to replace first occurrence of string in Java
I want to replace first occurrence of String in the following.
String test = "see Comments, this is for some test, help us"
**If test contains the input as follows it should not replace
- See Comments, (with space at the end)
- See comments,
- See Comments**
I want to get the output as follows,
Output: this is for some test, help us
Thanks in advance,
Solution 1:
You can use replaceFirst(String regex, String replacement)
method of String.
Solution 2:
You should use already tested and well documented libraries in favor of writing your own code.
org.apache.commons.lang3.
StringUtils.replaceOnce("coast-to-coast", "coast", "") = "-to-coast"
Javadoc
- https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#replaceOnce-java.lang.String-java.lang.String-java.lang.String-
There's even a version that is case insensitive (which is good).
Maven
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.7</version>
</dependency>
Credits
My answer is an augmentation of: https://stackoverflow.com/a/10861856/714112
Solution 3:
You can use following statement to replace first occurrence of literal string with another literal string:
String result = input.replaceFirst(Pattern.quote(search), Matcher.quoteReplacement(replace));
However, this does a lot of work in the background which would not be needed with a dedicated function for replacing literal strings.