Mike
Mike

Reputation: 755

Java String replace All Chars?

i am not familiar with regular expressions maybe one of you can help me. I have a String "46,50 EUR" or "-4.785,20 €" or something similar. I like to remove all chars that are not "0123456789.,-" I tried:

string betrag = "-4.785,20 €"; 
betrag = betrag.replaceAll("/[^0-9.,-]/", "");

but it wont work. The EUR-Sign will not be removed. Maybe it has something to do with the coding? utf-8 vs. latin1? Or my regular expression is wrong?

Upvotes: 0

Views: 97

Answers (2)

Maros
Maros

Reputation: 11

you can also use "/d" - it is shortcut for digital characters but of course the result is the same as mentioned by Tim

String betrag = "-4.785,20 €"; 
betrag = betrag.replaceAll("[^\d.,-]+", ""); 

by the way you can easily test your regular expression via some tools/websites - e.g.: https://www.freeformatter.com/java-regex-tester.html

Upvotes: 1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521239

Java's regex literals do not require delimiters, so remove the /:

String betrag = "-4.785,20 €"; 
betrag = betrag.replaceAll("[^0-9.,-]+", "");
System.out.println(betrag);  // -4.785,20

Upvotes: 2

Related Questions