110

I have a String and I want to extract the (only) sequence of digits in the string.

Example: helloThisIsA1234Sample. I want the 1234

It's a given that the sequence of digits will occur only once within the string but not in the same position.

(for those who will ask, I have a server name and need to extract a specific number within it)

I would like to use the StringUtils class from Apache commomns.

Thanks!

4
  • 1
    Apache StringUtils. Not sure why you wanna use it though. Commented Feb 20, 2013 at 7:02
  • That's what I have, was wondering if maybe there is a function already doing something like I need, but I am not so familiar with it Commented Feb 20, 2013 at 7:04
  • Cuz, when you can do it with String itself, you won't need the StringUtils from Apache. Commented Feb 20, 2013 at 7:11
  • This question is similar to: Extract digits from a string in Java. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. Commented Sep 11 at 14:09

20 Answers 20

212

Use this code numberOnly will contain your desired output.

   String str="sdfvsdf68fsdfsf8999fsdf09";
   String numberOnly= str.replaceAll("[^0-9]", "");
Sign up to request clarification or add additional context in comments.

2 Comments

String.replaceAll() would compile that pattern each time this is run. Really unoptimal. Check its source. Use Guava's CharMathcer.DIGIT.retainFrom() as seen below.
In more recent Java, the Regex can be simplified to "\\D"
40

I always like using Guava String utils or similar for these kind of problems:

String theDigits = CharMatcher.inRange('0', '9').retainFrom("abc12 3def"); // 123

3 Comments

This is a lot faster than regular expression. This should be the accepted answer.
use CharMatcher.digit().retainFrom("xx123xx"); instead, DIGIT is scheduled to be removed in June 2018.
CharMather.digit() is also deprecated. I used CharMatcher.inRange('0', '9').retainFrom("xx123xx");
28

Just one line:

int value = Integer.parseInt(string.replaceAll("[^0-9]", ""));

Comments

15

You can also use java.util.Scanner:

new Scanner(str).useDelimiter("[^\\d]+").nextInt()

You can use next() instead of nextInt() to get the digits as a String. Note that calling Integer.parseInt on the result may be many times faster than calling nextInt().

You can check for the presence of number using hasNextInt() on the Scanner.

1 Comment

In more recent Java, the Regex can be simplified to "\\D"
7

Use a regex such as [^0-9] to remove all non-digits.

From there, just use Integer.parseInt(String);

1 Comment

Sounds interesting, are you able to give me some more code? say my string var is called myString, how would I use it? (I am just a little new to Java...)
6

try this :

String s = "helloThisIsA1234Sample";
s = s.replaceAll("\\D+",""); // will return "1234"

This means: replace all occurrences of NON digital characters (other than: 0 -9) by an empty string !

1 Comment

It would be nice if you could add a little explanation as to what your code does. :)
5

Extending the best answer for finding floating point numbers

       String str="2.53GHz";
       String decimal_values= str.replaceAll("[^0-9\\.]", "");
       System.out.println(decimal_values);

Comments

4

Guava's CharMatcher class extracts Integers from a String.

String text="Hello1010";
System.out.println(CharMatcher.digit().retainFrom(text));

Yields:

1010

1 Comment

Deprecated as of 2022
3

I've created a JUnit Test class(as a additional knowledge/info) for the same issue. Hope you'll be finding this helpful.

   public class StringHelper {
    //Separate words from String which has gigits
        public String drawDigitsFromString(String strValue){
            String str = strValue.trim();
            String digits="";
            for (int i = 0; i < str.length(); i++) {
                char chrs = str.charAt(i);              
                if (Character.isDigit(chrs))
                    digits = digits+chrs;
            }
            return digits;
        }
    }

And JUnit Test case is:

 public class StringHelperTest {
    StringHelper helper;

        @Before
        public void before(){
            helper = new StringHelper();
        }

        @Test
    public void testDrawDigitsFromString(){
        assertEquals("187111", helper.drawDigitsFromString("TCS187TCS111"));
    }
 }

Comments

3

If you have access to org.apache.commons.lang3. you can use StringUtils.getDigits method

public static void main(String[] args) {
    String value = "helloThisIsA1234Sample";
    System.out.println(StringUtils.getDigits(value));
}
output: 12345

Comments

2
        String line = "This order was32354 placed for QT ! OK?";
        String regex = "[^\\d]+";

        String[] str = line.split(regex);

        System.out.println(str[1]);

Comments

2

You can use str = str.replaceAll("\\D+","");

Comments

2

You can split the string and compare with each character

public static String extractNumberFromString(String source) {
    StringBuilder result = new StringBuilder(100);
    for (char ch : source.toCharArray()) {
        if (ch >= '0' && ch <= '9') {
            result.append(ch);
        }
    }

    return result.toString();
}

Testing Code

    @Test
    public void test_extractNumberFromString() {
    String numberString = NumberUtil.extractNumberFromString("+61 415 987 636");
    assertThat(numberString, equalTo("61415987636"));

    numberString = NumberUtil.extractNumberFromString("(02)9295-987-636");
    assertThat(numberString, equalTo("029295987636"));

    numberString = NumberUtil.extractNumberFromString("(02)~!@#$%^&*()+_<>?,.:';9295-{}[=]987-636");
    assertThat(numberString, equalTo("029295987636"));
}

Comments

1

You can use the following regular expression.

string.split(/ /)[0].replace(/[^\d]/g, '')

1 Comment

Java is not JavaScript
1

Try this approach if you have symbols and you want just numbers:

    String s  = "@##9823l;Azad9927##$)(^738#";
    System.out.println(s=s.replaceAll("[^0-9]", ""));
    StringTokenizer tok = new StringTokenizer(s,"`~!@#$%^&*()-_+=\\.,><?");
    String s1 = "";
    while(tok.hasMoreTokens()){
        s1+= tok.nextToken();
    }
    System.out.println(s1);

1 Comment

This is now a slow solution, because String is immutable and in every cycle iteration is created new instance of String, replace at least with StringBuilder. Still it isn't write nice
1

If you want to handle decimal numbers and negative numbers you can use the following snippet:

Pattern pattern = Pattern.compile("-?\\d+(\\.\\d+)?");
Matcher matcher = pattern.matcher(mixedString);
String result = matcher.find() ? matcher.group() : null;

If you have a string like:

The temperature is -12.5°

The above code will extract a String containing "-12.5", that can be then parsed using parseFloat or parseInt.

Comments

0

A very simple solution, if separated by comma or if not separated by comma

public static void main(String[] args) {

    String input = "a,1,b,2,c,3,d,4";
    input = input.replaceAll(",", "");

    String alpha ="";
    String num = "";

    char[] c_arr = input.toCharArray();

    for(char c: c_arr) {
        if(Character.isDigit(c)) {
            alpha = alpha + c;
        }
        else {
            num = num+c;
        }
    }

    System.out.println("Alphabet: "+ alpha);
    System.out.println("num: "+ num);

}

Comments

-1
   `String s="as234dfd423";
for(int i=0;i<s.length();i++)
 {
    char c=s.charAt(i);``
    char d=s.charAt(i);
     if ('a' <= c && c <= 'z')
         System.out.println("String:-"+c);
     else  if ('0' <= d && d <= '9')
           System.out.println("number:-"+d);
    }

output:-

number:-4
number:-3
number:-4
String:-d
String:-f
String:-d
number:-2
number:-3

1 Comment

Your output doesn't appear to match your test input.
-1

You can try this:

  String str="java123java456";
  String out="";
  for(int i=0;i<str.length();i++)
  {
    int a=str.codePointAt(i);
     if(a>=49&&a<=57)
       {
          out=out+str.charAt(i);
       }
   }
 System.out.println(out);

2 Comments

From Review: Hi, please don't answer just with source code. Try to provide a nice description about how your solution works. See: How do I write a good answer?. Thanks
what about Capital letters or another languages?
-7

Simple python code for separating the digits in string

  s="rollnumber99mixedin447"
  list(filter(lambda c: c >= '0' and c <= '9', [x for x in s]))

1 Comment

this question has explicit Java tag

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.