sosumi
sosumi

Reputation: 67

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

Upvotes: 2

Views: 624

Answers (1)

Elliott Frisch
Elliott Frisch

Reputation: 201439

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

Upvotes: 5

Related Questions