Remove character from string

This example will show how to remove a character from a string using java, guava, apache commons and spring framework. This example could be used in conjunction with parsing a phone number if you need to remove all character references and convert to a number.

Straight up Java

Replace

This snippet will delete a character from a string using java's String.replace

@Test
public void remove_chars_from_java () {
    
    String parsedTelePhoneNumber = "920-867-5309".replace("-", "");
    assertEquals("9208675309", parsedTelePhoneNumber);
}

Replace all

This snippet will use a regular expression to remove special characters from a String by calling String.replaceAll.

@Test
public void remove_all_special_chars_from_java () {

    String parsedTelePhoneNumber = "+920-867-5309".replaceAll("[\\D]", "");
    assertEquals("9208675309", parsedTelePhoneNumber);
}

Google Guava

This snippet will use guava CharMatcher to define a range of characters and by calling retainFrom() will return a string containing all matching characters.

@Test
public void remove_char_from_string_guava() {

    String telephoneNumber = CharMatcher.inRange('0', '9').retainFrom(
            "920-867-5309");
    assertEquals("9208675309", telephoneNumber);

    // worried about performance?
    CharMatcher digits = CharMatcher.inRange('0', '9').precomputed();
    String teleNumber = digits.retainFrom("920-867-5309");
    assertEquals("9208675309", teleNumber);
}

Apache Commons

This snippet will removes all occurrences of a character from a string using apache commons StringUtils.remove.

@Test
public void remove_char_from_string_apache_commons() {

    String parsedTelephoneNumber = StringUtils.remove("920-867-5309", '-');

    assertEquals("9208675309", parsedTelephoneNumber);
}

Spring Framework

Using springframework, this snippet will replace all instances of a String with a String in a String, whoo, say that 10 times fast, it was hard to write!

@Test
public void remove_char_from_string_spring() {

    String parsedTelephoneNumber = org.springframework.util.StringUtils
            .replace("920-867-5309", "-", "");

    assertEquals("9208675309", parsedTelephoneNumber);
}