59

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

  1. See Comments, (with space at the end)
  2. See comments,
  3. See Comments**

I want to get the output as follows,

Output: this is for some test, help us
4
  • 14
    What have you tried? Commented Jun 5, 2012 at 12:40
  • 1
    You can goolge-search directly your question, or shift your eyes a little bit to the right of this comment and check the RELATED questions... Commented Jun 5, 2012 at 12:42
  • 1
    Or you could look at the documentation of String and find replaceFirst()... Commented Jun 5, 2012 at 12:46
  • Google will tell you how to replace the first occurrence of a REGEX, not a string. Commented Sep 11, 2016 at 4:14

7 Answers 7

106

You can use replaceFirst(String regex, String replacement) method of String.

Sign up to request clarification or add additional context in comments.

7 Comments

This is for REGEXes not, Strings.
@Sridhar-Sarnobat this is understood by the parameters I have mentioned in the Answer I guess? And that's how it is supposed to be used. .
This might be for regex, but will work even if you give a String instead of a builtup regex. I just tested. So the above discuss confuses people who see this. The answer is perfect.
What if you are trying to replace a string that contains -?
@Sridhar-Sarnobat when the search string contains pattern characters that are not supposed to be interpreted, you may filter the string through Pattern.quote(…) first. Though, it might be more efficient to use Pattern.compile(searchString, Pattern.LITERAL).matcher(input) .replaceAll(replacement) then…
|
23

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

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

2 Comments

I appreciate ur answer but because replaceFirst in String class is for regex. But just for one simple string replacement , I have to introduce a new library in my project. not worth .. any alternatives?
Yeah true, dynamically linked libraries are a pain. You could just copy and paste the library source code.
21

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.

3 Comments

This is the best answer, because it also handles regex characters and it not relies on external libs.
Unfortunately it does not work, try this: "I want to earn in euro!".replaceFirst(Pattern.quote("euro"), "$");
@FilipStachowiak fixed it.
14

Use substring(int beginIndex):

String test = "see Comments, this is for some test, help us";
String newString = test.substring(test.indexOf(",") + 2);
System.out.println(newString);

OUTPUT:

this is for some test, help us

1 Comment

Wait, what if the string you want to replace isn't at the beginning of the input string?
3

You can use following method.

public static String replaceFirstOccurrenceOfString(String inputString, String stringToReplace,
        String stringToReplaceWith) {

    int length = stringToReplace.length();
    int inputLength = inputString.length();

    int startingIndexofTheStringToReplace = inputString.indexOf(stringToReplace);

    String finalString = inputString.substring(0, startingIndexofTheStringToReplace) + stringToReplaceWith
            + inputString.substring(startingIndexofTheStringToReplace + length, inputLength);

    return finalString;

}

Following link provide examples for replacing first occurrence of string using with and without regular expressions.

Comments

-1

Use String replaceFirst to swap the first instance of the delimiter to something unique:

String input = "this=that=theother"
String[] arr = input.replaceFirst("=", "==").split('==',-1);
String key = arr[0];
String value = arr[1];
System.out.println(key + " = " + value);

Comments

-1

You can also use this method in node.js;

public static String replaceFirstOccurance(String str, String chr, String replacement){
    String[] temp = str.split(chr, 2);
    return temp[0] + replacement + temp[1];
}

1 Comment

That doesn't work, split works on regex-es.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.