Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

  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 

Thanks in advance,

like image 448
Jagadeesh Avatar asked Jun 05 '12 12:06

Jagadeesh


People also ask

How do I change the first occurence of a string?

Use the replace() method to replace the first occurrence of a character in a string. The method takes a regular expression and a replacement string as parameters and returns a new string with one or more matches replaced. Copied!

How do I change the first word in Java?

The Java String replaceFirst() method replaces the first substring 'regex' found that matches the given argument substring (or regular expression) with the given replacement substring. The substring matching process start from beginning of the string (index 0).

How do you replace part of a string in Java?

You can replace a substring using replace() method in Java. The String class provides the overloaded version of the replace() method, but you need to use the replace(CharSequence target, CharSequence replacement).

How to replace first occurrence of a substring with another in Java?

Java – How to Replace First Occurrence of a Substring with Another in String? To replace the first occurrence of a string old_string in str1 with new_string, you can use str1.replaceFirst (old_string, new_string) function.

How to replace the first character in a string in Java?

We can use the Java String substring function to replace the first character occurrence. In this Java program, repstCharStr.substring (0, i) returns substring up to the index position of the replace_ch character.

How to use replace () in Java function?

Let’s understand replace () in Java function with an example: Java String replaceAll () method finds all occurrences of sequence of characters matching a regular expression and replaces them with the replacement string. At the end of call, a new string is returned by the function replaceAll () in Java.

How do you replace a string with a new string?

Java String replace () Method Java String replace () method replaces every occurrence of a given character with a new character and returns a new string. The Java replace () string method allows the replacement of a sequence of character values.


1 Answers

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

like image 108
Asif Avatar answered Sep 23 '22 20:09

Asif