"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Extract Digits from Strings in Java?

How to Extract Digits from Strings in Java?

Posted on 2025-03-25
Browse:263

How to Extract Digits from Strings in Java?

Extracting Digits from Strings in Java

When working with strings in Java, there may arise a need to extract only the numerical digits. This operation can be achieved using various approaches, including regular expressions.

Regular Expressions

One efficient method is to utilize the replaceAll method with a regular expression that matches non-digits (\\D ) and replaces them with an empty string. For instance:

String str = "123-456-789";
str = str.replaceAll("\\D ",""); // Result: "123456789"

This approach effectively removes all characters except for digits from the string, resulting in the desired output.

Additional Libraries

The replaceAll method is part of the Java String class and does not require the installation of any additional libraries. It is a built-in feature of the Java programming language.

Conclusion

Extracting digits from strings in Java can be conveniently accomplished using regular expressions, which provide a powerful tool for manipulating and parsing text data. The replaceAll method, coupled with the appropriate regular expression, enables efficient digit extraction without the need for additional libraries.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3