In this article, we’ll go through how you can replace either a character or a string inside a String in Java.
1. Java String Replace without Regex.
In this section, we’ll go through the two methods String
class provides us for replacing either a character or a string.
1.1. Replace a Character Using replace(Character oldChar, Character newChar)
The String
class in Java provides a replace()
method that accepts the char
to be replaced and the replacement. Note that all characters matched will be replaced.
String clh = "Code Learn Hub"; clh = clh.replace('e', 'a'); System.out.println(clh);
Of course, the output of the above will be “Coda Laarn Hub
” since ‘e’ was found and replaced by ‘a’ two times.
1.2. Replace a String Using replace(CharSequence old, CharSequence new)
You can replace strings inside strings by using the overloaded method of replace()
which accepts two strings, the first one is the string to be replaced and the second one is the replacement.
String hello = "Hello world and Hello world"; hello = hello.replace("Hello", "Bye"); System.out.println(hello);
The snippet above will print “Bye world and Bye world
“.
2. Java String Replace with Regex
In this section, we’ll go through replaceAll()
and replaceFirst()
methods that String
class provides us, in order to replace characters inside a string based on regex matching.
2.1 Replace All Occurences Using replaceAll() Method
The method replaceAll accepts a regex to be matched in order for the replacement to happen, and of course, a string that will be the replacement.
String clh = "Code 7Learn4 Hub9"; clh = clh.replaceAll("[0-9]", "5"); System.out.println(clh); // This will print Code 5Learn5 Hub5
As you can observe, with replaceAll()
, when the regex [0-9]
is matched (this matches any single-digit number), all of the occurrences matched will be replaced.
2.2 Replace Only the First Matched Regular Expression Using replaceFirst()
If we want only the first matching of regex to be replaced we should use replaceFirst()
.
String hello = "Hello15 world and Hello world50"; hello = hello.replaceFirst("\\d+", "100"); System.out.println(hello); // It will print Hello100 world and Hello world50
As you can observe in the example above when regex \\d
is matched (this matches any number), only the first match will be replaced and the rest will be ignored.
3. Conclusion
By now you should be able to replace any character or string by using the replace methods of String class. You can find the source code of the examples on our GitHub page.