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+\\", "-");
}