javastringapache-stringutilsstring-utils

Extract digits from string - StringUtils Java


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!


Solution

  • Use this code numberOnly will contain your desired output.

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