Home > Java > javaTutorial > body text

How to Remove Non-Numeric Characters from a String While Preserving Decimal Separators in Java?

DDD
Release: 2024-11-02 03:11:02
Original
930 people have browsed it

How to Remove Non-Numeric Characters from a String While Preserving Decimal Separators in Java?

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>
Copy after login

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!