Home >Java >javaTutorial >How to Keep Decimal Separators When Removing Non-Numeric Characters in Java?

How to Keep Decimal Separators When Removing Non-Numeric Characters in Java?

Susan Sarandon
Susan SarandonOriginal
2024-11-03 07:40:30501browse

How to Keep Decimal Separators When Removing Non-Numeric Characters in Java?

Keep Decimal Separator While Removing Non-Numeric Characters

Removing non-numeric characters from a string is a prevalent task in many programming scenarios. However, maintaining the decimal separator during this operation can be crucial to preserve the mathematical integrity of the string. Here's a Java approach that effectively solves this problem:

Using the replaceAll() method, you can replace all characters that are not digits or the decimal separator with an empty string. Consider the following code:

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

In this code, the [^\d.] regular expression matches any character that is not a digit or a decimal separator. As a result, the final value of str will be "12.334.78", where all non-numeric characters have been removed while preserving the decimal separator.

The above is the detailed content of How to Keep Decimal Separators When Removing Non-Numeric Characters 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