How to Remove Non-Numeric Characters from a String While Preserving Decimal Separators in Java
When working with strings that contain both numeric and non-numeric characters, it becomes necessary to remove the latter while preserving the decimal separators. Achieving this requires a specific approach.
Problem:
The goal is to eliminate all characters that are not digits (0-9) from a string. However, the challenge arises when it comes to maintaining the decimal separator. By default, using Character.isDigit() removes both letters and the decimal separator.
Solution:
To address this issue, a combination of regular expressions and string manipulation can be employed:
<code class="java">String str = "a12.334tyz.78x"; str = str.replaceAll("[^\d.]", "");</code>
This code utilizes the replaceAll method from the String class. The regular expression [^\d.] matches all characters that are not digits or periods. By replacing these with an empty string, the resulting string str will contain only the numeric characters and decimal separators.
For example, given the input string "a12.334tyz.78x," the output string will be "12.334.78," where all non-numeric characters have been removed while retaining the decimal points.
The above is the detailed content of How to Remove Non-Numeric Characters from a String While Preserving Decimal Separators in Java?. For more information, please follow other related articles on the PHP Chinese website!