Trying to remove all letters and characters that are not 0-9 and a period. I'm using Character.isDigit()
but it also removes decimal, how can I also keep the decimal?

- 303,325
- 100
- 852
- 1,154

- 6,825
- 6
- 29
- 45
-
5[myStr = myStr.replaceAll( "\[^\\d\]", "" )][1] [1]: http://stackoverflow.com/questions/1533659/how-do-i-remove-the-non-numeric-character-from-a-string-in-java – Bitmap Apr 29 '12 at 14:30
-
2This is a strange way to say this. Isn't "all letters and characters that are not 0-9 and a period" equivalent to simpler "all characters that are not 0-9 and a period"? I mean, letters are characters which are not 0-9 nor the period. – Adam Zalcman Apr 29 '12 at 14:30
11 Answers
Try this code:
String str = "a12.334tyz.78x";
str = str.replaceAll("[^\\d.]", "");
Now str
will contain "12.334.78"
.

- 76,112
- 17
- 94
- 154

- 232,561
- 37
- 312
- 386
-
26This could also work: > str = str.replaceAll("[\\D.]", ""); – yeaaaahhhh..hamf hamf Jan 26 '15 at 14:39
-
1@Óscar López: how to include negative numbers also? I mean, I have to replace everything that is not a positive/negative number with an empty space. How to do that? – Pankaj Singhal Sep 06 '15 at 09:07
-
4@PankajSinghal simply include the minus sign in the regex: `[^\\d.-]` – Óscar López Sep 06 '15 at 14:36
-
4@yeaaaahhhh..hamfhamf no, that won't work. We have to negate the whole group (including numbers and dots), your suggested code only negates the numbers, and the result won't include dots, as required. Did you _test_ it? using the sample code above, your code returns `"1233478"`, which is incorrect. – Óscar López Sep 06 '15 at 14:42
-
-
i have a array with of numbers and char in it i.e [1,4,7,a,6,d,9,3,5]. I want to filter out all the char from the array. what should i do? – Dishank Jindal Feb 14 '18 at 15:35
-
-
-
-
I would use a regex.
String text = "-jaskdh2367sd.27askjdfh23";
String digits = text.replaceAll("[^0-9.]", "");
System.out.println(digits);
prints
2367.2723
You might like to keep -
as well for negative numbers.

- 525,659
- 79
- 751
- 1,130
-
-
Could you please put some explanation for what does `^` and `.` mean in this statement? – Mansour Fahad Aug 19 '14 at 15:32
-
2@MansourFahad In a regex `[^` means not these characters and inside a `[]` a `.` is just a `.` – Peter Lawrey Aug 19 '14 at 20:42
-
1Since a `.` is just a `a` and doesn’t mean anything, can I just get rid of it? – Mansour Fahad Aug 24 '14 at 11:41
-
-
this answer is good but small update for newer dart versions. `text.replaceAll(RegExp("[^0-9.]"), "");` – l1nuxuser Jul 02 '19 at 10:14
Solution
With dash
String phoneNumberstr = "Tel: 00971-557890-999";
String numberRefined = phoneNumberstr.replaceAll("[^\\d-]", "");
Result: 0097-557890-999
.
Without dash
If you also do not need "-" in String you can do like this:
String phoneNumberstr = "Tel: 00971-55 7890 999";
String numberRefined = phoneNumberstr.replaceAll("[^0-9]", "");
Result: 0097557890999
.

- 17,291
- 7
- 48
- 81

- 3,946
- 39
- 35
With guava:
String input = "abx123.5";
String result = CharMatcher.inRange('0', '9').or(CharMatcher.is('.')).retainFrom(input);
see http://code.google.com/p/guava-libraries/wiki/StringsExplained

- 10,475
- 1
- 43
- 50
-
@egorikem if your project is already using guava, you can use it at no extra cost.. – stan Feb 19 '19 at 16:04
str = str.replaceAll("\\D+","");

- 10,403
- 14
- 67
- 117

- 334
- 2
- 6
-
Dunno why people downvoted your solution... Helped me alot, thanks! Votes up! – Zarial Apr 10 '17 at 10:34
-
Thanks Zarial, I see Robert actually edited my answer from str = str.replaceAll("\D+",""); to str = str.replaceAll("\\D+",""); ... So i made this mistake when pasting it into StackO's editor box thingy. So thank you Robert for fixing. Now it works! – Angoranator777 Oct 19 '17 at 23:26
-
it's downvoted cause it's a repost. Exact same answer has already been sublitted 5 years ago !! see above : https://stackoverflow.com/a/10372905/704246 – Saad Benbouzid Dec 13 '17 at 15:50
-
@SaadBenbouzid huh? what is your definition of the exact same answer? – Boris Treukhov Jan 31 '18 at 16:36
-
@BorisTreukhov see comment from "yeaaaahhhh..hamf hamf" from "Jan 26 '15 at 14:39" on the same page – Saad Benbouzid Jan 31 '18 at 17:03
-
4@SaadBenbouzid 1) that is comment and not an answer 2) that is a completely different regex 3) not all answers which use regex D are identical it's like pointing that all C language answers which use `printf()` are duplicates. Also if you see an answer in comment you can ask mod to convert it to an answer or even add an answer on your own - answers in comments are discouraged on StackOverlow. – Boris Treukhov Jan 31 '18 at 17:20
Simple way without using Regex:
Adding an extra character check for dot '.'
will solve the requirement:
public static String getOnlyNumerics(String str) {
if (str == null) {
return null;
}
StringBuffer strBuff = new StringBuffer();
char c;
for (int i = 0; i < str.length() ; i++) {
c = str.charAt(i);
if (Character.isDigit(c) || c == '.') {
strBuff.append(c);
}
}
return strBuff.toString();
}

- 7,326
- 3
- 41
- 61
-
1Since the `StringBuffer` is only being used inside the function, and not shared between threads, it would be recommended, for performance reasons, to use `StringBuilder`, instead. See: https://stackoverflow.com/a/4793503/679240 and https://stackoverflow.com/a/2771852/679240 – Haroldo_OK Feb 24 '22 at 12:35
Currency decimal separator can be different from Locale to another. It could be dangerous to consider .
as separator always.
i.e.
╔════════════════╦═══════════════════╗
║ Locale ║ Sample ║
╠════════════════╬═══════════════════╣
║ USA ║ $1,222,333.44 USD ║
║ United Kingdom ║ £1.222.333,44 GBP ║
║ European ║ €1.333.333,44 EUR ║
╚════════════════╩═══════════════════╝
I think the proper way is:
- Get decimal character via
DecimalFormatSymbols
by default Locale or specified one. - Cook regex pattern with decimal character in order to obtain digits only
And here how I am solving it:
code:
import java.text.DecimalFormatSymbols;
import java.util.Locale;
public static String getDigit(String quote, Locale locale) {
char decimalSeparator;
if (locale == null) {
decimalSeparator = new DecimalFormatSymbols().getDecimalSeparator();
} else {
decimalSeparator = new DecimalFormatSymbols(locale).getDecimalSeparator();
}
String regex = "[^0-9" + decimalSeparator + "]";
String valueOnlyDigit = quote.replaceAll(regex, "");
try {
return valueOnlyDigit;
} catch (ArithmeticException | NumberFormatException e) {
Log.e(TAG, "Error in getMoneyAsDecimal", e);
return null;
}
return null;
}
I hope that may help,'.

- 17,493
- 11
- 81
- 103
-
Although this was not asked, but this is the only solution that works with localization. – Herrbert74 Sep 25 '20 at 09:19
For the Android folks coming here for Kotlin
val dirtyString = " Account Balance: $-12,345.67"
val cleanString = dirtyString.replace("[^\\d.]".toRegex(), "")
Output:
cleanString = "12345.67"
This could then be safely converted toDouble()
, toFloat()
or toInt()
if needed

- 9,639
- 3
- 64
- 69
A way to replace it with a java 8 stream:
public static void main(String[] args) throws IOException
{
String test = "ab19198zxncvl1308j10923.";
StringBuilder result = new StringBuilder();
test.chars().mapToObj( i-> (char)i ).filter( c -> Character.isDigit(c) || c == '.' ).forEach( c -> result.append(c) );
System.out.println( result ); //returns 19198.130810923.
}

- 920
- 5
- 16
The below code should remove all non-digit characters and allow periods.
String newString = currentString.replaceAll("[\\D.]", "");

- 73
- 4
This handles null inputs, negative numbers and decimals (you need to include the Apache Commons Lang library, version 3.8 or higher, in your project):
import org.apache.commons.lang3.RegExUtils;
result = RegExUtils.removeAll(input, "-?[^\\d.]");
Library reference: https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/RegExUtils.html

- 722
- 7
- 14