Home > Java > javaTutorial > How Can I Remove Non-Numeric Characters from a Java String While Preserving Decimals?

How Can I Remove Non-Numeric Characters from a Java String While Preserving Decimals?

Susan Sarandon
Release: 2024-11-02 04:22:02
Original
699 people have browsed it

How Can I Remove Non-Numeric Characters from a Java String While Preserving Decimals?

Removing Non-Numeric Characters while Preserving Decimals in Java Strings

Removing all non-numeric characters from a string can be useful in various scenarios. However, methods like Character.isDigit() may overlook the decimal separator, resulting in loss of important data.

To address this issue, consider employing a regular expression-based approach. The regular expression "[^\d.]" matches any character that is not a digit (0-9) or a decimal point (period).

For instance, given the string "a12.334tyz.78x", the following code snippet will effectively purge all non-numeric characters, preserving the decimal separators:

<code class="java">String str = "a12.334tyz.78x";
str = str.replaceAll("[^\d.]", "");</code>
Copy after login

After executing the above code, str will contain the modified string "12.334.78", where all letters and special characters are eliminated, while the decimal separators remain intact.

The above is the detailed content of How Can I Remove Non-Numeric Characters from a Java String While Preserving Decimals?. 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