I want to use replaceAll() in a String to remove everything except numbers. So far it does work:
String text = "578343NumberString487gd34";
text = text.replaceAll("[^\\d]", "");
This removes everything except the numbers. After this I turn it into an Integer.
Now the problem is that the number I want to get is not an Integer, but a Double. But if I add a '.' or a ',' to the String, it gets deleted too. That's not what I want. Is there a way to replace all non-numeric values except for these?
CodePudding user response:
Use a character class to preserve digits, dots and commas:
text = text.replaceAll("[^\\d.,]", "");
CodePudding user response:
String text = "340314randomText054934.43";
double finalNumber;
text = text.replaceAll("[^\\d.,]", "");
finalNumber = Double.parseDouble(text);
It worked with replaceAll("[^\\d.,]", ""). Thanks to everyone who helped me!