Java String replace(), replaceAll() and replaceFirst()
- replace() uses literal strings (no regex) and replaces all occurrences. Use it when you want literal substitution.
- replaceAll() uses regex for the first argument. Special regex characters (., |, +, *, ?) must be escaped with \\ when you want them treated literally.
- replaceFirst() replaces only the first regex match β useful for log prefix replacement or structured string editing.
replace() vs replaceAll() is a genuine source of bugs. Both replace all occurrences. The difference is the first argument: replace() treats it as a literal string; replaceAll() treats it as a regex. Passing a string like '.' to replaceAll() when you mean a literal dot will produce very surprising results.
replace(), replaceAll(), and replaceFirst() with Examples
package io.thecodeforge.strings; public class StringReplaceExample { public static void main(String[] args) { String url = "https://thecodeforge.io/payment/service/docs"; // replace(char, char) β single character replacement String noSlashes = url.replace('/', '-'); System.out.println(noSlashes); // https:--thecodeforge.io-payment-service-docs // replace(String, String) β literal string, all occurrences String http = url.replace("https", "http"); System.out.println(http); // http://thecodeforge.io/payment/service/docs // replaceAll(regex, replacement) β regex-powered, all occurrences String camelCase = "paymentRetryService"; // Insert underscore before each uppercase letter String snakeCase = camelCase.replaceAll("([A-Z])", "_$1").toLowerCase(); System.out.println(snakeCase); // payment_retry_service // replaceAll with DOT β common bug String dotted = "192.168.1.1"; System.out.println(dotted.replaceAll(".", "X")); // XXXXXXXXXX β dot = any char! System.out.println(dotted.replaceAll("\\.", "X")); // 192X168X1X1 β escaped dot System.out.println(dotted.replace(".", "X")); // 192X168X1X1 β safer for literal // replaceFirst() β only the first match String log = "ERROR:101 ERROR:102 ERROR:103"; System.out.println(log.replaceFirst("ERROR", "WARN")); // WARN:101 ERROR:102 ERROR:103 // replaceAll for removing whitespace String messy = " payment service "; String clean = messy.replaceAll("\\s+", " ").trim(); System.out.println(clean); // payment service // Replacing special regex chars in replacement string: use \\$ for literal $ String price = "Amount: $100"; System.out.println(price.replaceAll("\\$", "USD ")); // Amount: USD 100 } }
http://thecodeforge.io/payment/service/docs
payment_retry_service
XXXXXXXXXX
192X168X1X1
192X168X1X1
WARN:101 ERROR:102 ERROR:103
payment service
Amount: USD 100
| Method | First Arg Type | Replaces | Regex? |
|---|---|---|---|
| replace(char, char) | Literal char | All occurrences | No |
| replace(String, String) | Literal string | All occurrences | No |
| replaceAll(regex, str) | Regex pattern | All matches | Yes |
| replaceFirst(regex, str) | Regex pattern | First match only | Yes |
π― Key Takeaways
- replace() uses literal strings (no regex) and replaces all occurrences. Use it when you want literal substitution.
- replaceAll() uses regex for the first argument. Special regex characters (., |, +, *, ?) must be escaped with \\ when you want them treated literally.
- replaceFirst() replaces only the first regex match β useful for log prefix replacement or structured string editing.
- When in doubt between replace() and replaceAll() for literal substitution, prefer replace() β it's safer and avoids unintended regex interpretation.
β Common Mistakes to Avoid
- βUsing replaceAll(".", "X") to replace dots β dot in regex matches any character. Use replace(".", "X") for literal dot replacement, or replaceAll("\\.", "X").
- βUsing replaceAll("|", ...) for pipe characters β pipe is regex OR. Use replace("|", ...) or replaceAll("\\|", ...).
- βForgetting that replace() (not replaceAll()) also replaces ALL occurrences β the method name doesn't say 'all' but it does replace every match.
Interview Questions on This Topic
- QWhat is the difference between String.replace() and String.replaceAll() in Java?
- QWhat does 'hello.world'.replaceAll('.', 'X') return, and why?
Frequently Asked Questions
What is the difference between Java String replace() and replaceAll()?
Both replace all occurrences. The difference is the first argument: replace() treats it as a literal character or string. replaceAll() treats it as a regular expression. Use replace() for simple literal substitutions. Use replaceAll() when you need regex power, but remember to escape special regex characters.
Why does replaceAll('.', 'X') replace every character in Java?
The dot in a regular expression means 'match any character'. replaceAll('.', 'X') matches every single character in the string and replaces each with X. To replace a literal dot, either use replace('.', 'X') or replaceAll('\\.', 'X').
Developer and founder of TheCodeForge. I built this site because I was tired of tutorials that explain what to type without explaining why it works. Every article here is written to make concepts actually click.