The method replaceAll() replaces all occurrences of a String in another String matched by regex.

This is similar to the replace() function, the only difference is, that in replaceAll() the String to be replaced is a regex while in replace() it is a String.

Available Signatures

public String replaceAll(String regex, String replacement)

Example

@Test
void whenReplaceAll_thenCorrect() {
    String s = "my url with spaces";

    assertEquals("my-url-with-spaces", s.replaceAll("\\s+", "-"));
    assertEquals("your url with spaces", s.replaceAll("my", "your"));
}

Throws

  • PatternSyntaxException – if regex is invalid
@Test(expected = PatternSyntaxException.class)
void whenInvalidRegex_thenPatternSyntaxExceptionThrown() {
    String s = "my url with spaces";

    s.replaceAll("\\s+\\", "-");
}
Next »
Java String.split()
« Previous
Java String.replace()
Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.