Extract digits from string - StringUtils Java

NinaNa picture NinaNa · Feb 20, 2013 · Viewed 221.4k times · Source

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!

Answer

user1999257 picture user1999257 · Feb 20, 2013

Use this code numberOnly will contain your desired output.

   String str="sdfvsdf68fsdfsf8999fsdf09";
   String numberOnly= str.replaceAll("[^0-9]", "");