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()
Java bottom

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

>> CHECK OUT THE COURSE
Generic footer banner
Comments are closed on this article!