Home > Java > javaTutorial > How to Extract Digits from Strings in Java?

How to Extract Digits from Strings in Java?

DDD
Release: 2024-11-02 07:48:29
Original
1036 people have browsed it

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:

<code class="java">String str = "123-456-789";
str = str.replaceAll("\D+",""); // Result: "123456789"</code>
Copy after login

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.

The above is the detailed content of How to Extract Digits from Strings in Java?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template