Replace all non digits with an empty character in a string
Asked Answered
C

5

20
public static String removeNonDigits(final String str) {
   if (str == null || str.length() == 0) {
       return "";
   }
   return str.replaceAll("/[^0-9]/g", "");
}

This should only get the Digits and return but not doing it as expected! Any suggestions?

Cannon answered 28/9, 2009 at 10:9 Comment(1)
If you look at String.replaceAll method, you will see that it's doing Pattern.compile(regex).matcher(this).replaceAll(replacement) which is inefficient if you are doing this a lot. A better way would be to extract the compiled pattern into a constant.Hagans
F
50

Java is not Perl :) Try "[^0-9]+"

Fatima answered 28/9, 2009 at 10:13 Comment(7)
@whyoz: Please ask a new questionFatima
@whyoz: No one is ever going to find the answer in a comment.Fatima
"[^0-9.]+" will keep the decimal, if you happened upon this post needing to do soGagarin
I wish a Perl regular expressions in JavaDoubleteam
@AaronDigulla: 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?Ferrick
@PankajSinghal: I'm almost sure this isn't possible with regexp. I suggest to ask a new question, maybe someone knows a trick.Fatima
@AaronDigulla I asked a question on this. Seems it's possible. :)Ferrick
S
18

Try this:

public static String removeNonDigits(final String str) {
   if (str == null || str.length() == 0) {
       return "";
   }
   return str.replaceAll("\\D+", "");
}
Saleme answered 28/9, 2009 at 10:15 Comment(1)
You need to escape the slash (for Java's sake, not the regex): "\\D+"Dowsabel
F
7

Use following where enumValue is the input string.

enumValue.replaceAll("[^0-9]","")

This will take the string and replace all non-number digits with a "".

eg: input is _126576, the output will be 126576.

Hope this helps.

Footstalk answered 10/7, 2012 at 8:37 Comment(0)
F
2
public String replaceNonDigits(final String string) {
    if (string == null || string.length() == 0) {
        return "";
    }
    return string.replaceAll("[^0-9]+", "");
}

This does what you want.

Framework answered 28/9, 2009 at 10:49 Comment(0)
G
-1

I'd recommend for this particular case just having a small loop over the string.

StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
    char ch = s.charAt(i);
    if (ch =='0' || ch == '1' || ch == '2' ...) {
        sb.add(ch);
    }
}
return sb.toString();
Gaiseric answered 28/9, 2009 at 12:10 Comment(1)
Character.isDigit(...) is a better option than '(ch =='0' || ch == '1' || ch == '2'....)' IMO.Mysticism

© 2022 - 2024 — McMap. All rights reserved.