Home > Java > javaTutorial > body text

How can I Extract Digits from a String in Java?

Mary-Kate Olsen
Release: 2024-11-02 20:08:30
Original
576 people have browsed it

How can I Extract Digits from a String in Java?

Extracting Digits from Strings in Java

In Java, extracting digits from a string can be achieved using various methods. One common approach involves utilizing regular expressions to identify and remove non-digit characters.

Method:

  1. Start with a Java string containing both digits and non-digits.
  2. Use the replaceAll() method to search for all non-digit characters in the string using the regular expression "\D ".
  3. Replace the non-digits with an empty string, effectively removing them from the string.

Example:

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

Note:

This method does not require the installation of any additional libraries as it uses built-in Java features.

The above is the detailed content of How can I Extract Digits from a String 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template