backward slash always needs to be escaped. The StringUtils class has methods for replacing a substring of a String: There is an overloaded variant of the replace() that takes an integer max parameter, which determines the number of occurrences to replace. With the help of these you can replace characters in your string. This method returns a new string resulting from replacing all occurrences of oldChar in this string with newChar. One of the simplest and straightforward methods of replacing a substring is using the replace, replaceAll or replaceFirst of a String class. Enclosing the desired word inside this regular expression will only match exact occurrences. THE unique Spring Security education if you’re working with Java today. Another method we'll consider is the Apache Commons library. As their name implies, replaceAll() will replace every matched occurrence, while the replaceFirst() will replace the first matched occurrence: It's because the regex supplied as regexTarget will only match the last occurrence of Baeldung. Steve flies like a tiny ad: current ranch time (not your local time) is, How to replace the backslash with the forward slash using java, Grokking Artificial Intelligence Algorithms, https://coderanch.com/t/674455/Thread-Boost-feature, String replaceAll method removes backslashes in replacement string. As a bonus, we'll also look into replacing an exact word using the String API and the Apache Commons RegExUtils class. In all examples given above, we can use an empty replacement and it'll effectively remove a target from a master. We'll explore removing and/or replacing a substring using a String API, then using a StringBuilder API and finally using the StringUtils class of Apache Commons library. Regular expressions can be used to perform all types of text search and text replace operations. We can also use the replaceIgnoreCase() if case-sensitivity is not a concern: In this last example, we'll learn how to replace an exact word inside a String. We can also manipulate text in Java using the StringBuilder class. First, let's see how to use this regular expression with the String API: Only the exact word will be replaced. If you want to replace a single backslash in Java using replaceAll there are multiple layers of escaping that leads to four backslashes as an argument for replaceAll.. First, let's add the required dependency to our project: The latest version of the library can be found here. Java - String replace() Method. You can always update your selection by clicking Cookie Preferences at the bottom of the page. We need to run same Java applications in cross platforms say Windows, Linux etc. this forum made possible by our volunteer staff, including ... You can also use this method which works without regexps: Time flies like an arrow.