Home  >  Article  >  Java  >  How can I Extract Digits from a String in Java?

How can I Extract Digits from a String in Java?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-02 20:08:30506browse

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>

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!

Statement:
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