getDigits
is a static method of the StringUtils
class that checks for Unicode digits in a string and returns a new string that contains all the digits in the given string. If the given string does not contain any digits, an empty string will be returned.
StringUtils
StringUtils
is defined in the Apache Commons Lang package. Apache Commons Lang can be added to the Maven project by adding the following dependency to the pom.xml
file.
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
For other versions of the commons-lang package, refer to the Maven Repository.
You can import the StringUtils
class as follows.
import org.apache.commons.lang3.StringUtils;
public static String getDigits(final String str)
str
: the string to extract the digits from.The method returns a new string that contains only the digits present in the given string.
import org.apache.commons.lang3.StringUtils;public class Main {public static void main(String[] args) {String s = "hello educative123. Hello 345,68, mic check";System.out.printf("The digit string of \"%s\" is \"%s\"", s, StringUtils.getDigits(s));System.out.println();s = "hello educative";System.out.printf("The digit string of \"%s\" is \"%s\"", s, StringUtils.getDigits(s));}}
The digit string of "hello educative123. Hello 345,68, mic check" is "12334568"
The digit string of "hello educative" is ""
hello educative123. Hello 345,68, mic check
The method will return 12334568
, extracting all the digits and forming a string while the order of occurrence of the digits is preserved.
hello educative
The method will return an empty string as there are no digits in the string.