Explain Codes LogoExplain Codes Logo

Replace all substrings in Java without RegEx

java
string-manipulation
regex
performance
Alex KataevbyAlex Kataev·Jan 18, 2025
TLDR

To swap substrings without regex, use String.replace(target, replacement). It directly changes all instances of target to replacement.

Example:

String result = "fooBar".replace("Bar", "Baz"); // "fooBaz". Because "Bar" is just too mainstream.

Remember: String.replace works without regex, unlike String.replaceAll.

To deal with non-literal patterns, escape special characters using Pattern.quote. This makes sure String.replaceAll treats every character as literal.

String result = "fooBar$".replaceAll(Pattern.quote("Bar$"), "Baz"); // "fooBaz". Yeah, that's right. The dollar sign ($) also deserves a vacation.

This offers safety against unexpected pattern matching behaviors.

Distinguishing replace and replaceAll

Define the thin line between String.replace and String.replaceAll:

  • String.replace: Seeks and replaces literal substrings without any regex interpretation.
  • String.replaceAll: Embraces regex and patterns to make matches.

Performance Watch: When dealing with direct replacements, String.replace is snappier as it skips regex processing.

Keeping Escaping at Bay

Use Pattern.quote to escape special characters in cases where you still need String.replaceAll.

String escapedTarget = Pattern.quote("$pecialChars$"); String result = "Use $pecialChars$ wisely".replaceAll(escapedTarget, "regular chars"); // "Use regular chars wisely". We should definitely have a meetup for these chars.

Remember: Special characters include . ^ $ * + - ? ( ) [ ] { } | and \\. They are like the Avengers, but for patterns!

Road to Rich Replacements

Sophisticated text manipulations may require StringUtils from Apache Commons or Google Guava's Utilities.

StringUtils: Bring in replaceEach for Hulk-like multiple replacements. Google Guava: Offers wizards like Strings.isNullOrEmpty and Splitter for level-up string operations.

Code at Work

Now, let's watch the code behave like a well-behaved classroom.

String result = "FooBar".replace("bar", "Baz"); // "FooBar". Unfortunately, "bar" missed the attendance.

To replace case-insensitively: Play uniform, bring both strings to the same case, or use Pattern.compile with Pattern.CASE_INSENSITIVE.

Don't Fall into the Traps

Mind the common errors like mixing methods, forgetting null checks, or missing character escaping.

  • Method Mixer: Maintain good diet. Do not mix up String.replace with String.replaceAll.
  • Null Predator: Do guard duty. Check that target and replacement strings aren't null.
  • Escaping Ninjas: If using String.replaceAll, the special characters might play hide 'n' seek. Escape them!