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!