Search code examples
javaregexnumbersreplaceall

Remove everything from a string except . and numbers through 0-9 - Java


I am trying to read a line of text and remove everything besides periods and numbers through 0 - 9.

This is what I am trying but It removes everything except spaces.

distance.replaceAll("[^0-9 + \\.]", "");

Solution

  • A literal . is . (and an escape is \\ not one \), and you can use \\d for digits. Like,

    String distance = "123zz.0";
    System.out.println(distance.replaceAll("[^\\d.]", ""));
    

    Outputs (as requested)

    123.0